<?php
namespace app\app\controller;
use think\Db;
class User extends Common
{
    //获取用户资料
    public function get_info()
    {
        $token = request()->request('token');
        $uid = token_decode($token);
        $msg['state'] = 1;
        $msg['data'] = Db::table('user')->field('name,phone,headimg,sex')->where('id', $uid)->find();
        $this_time=time();
        $msg['data']['discounts_number']= Db::table('user_discounts')->where(['uid' => $uid, 'status' =>1])->where('due_date>=' . $this_time)->count();
       
        $msg['msg'] = '获取成功';
        return json($msg);
    }

    //保存个人资料   user/save_info 保存用户个人资料
    public function save_info()
    {
        $token = request()->request('token');
        $uid = token_decode($token);
        $msg['state'] = 1;
        $msg['data'] = '';
        $data['name'] = request()->request('name');
        $data['sex'] = request()->request('sex');
        if ($_FILES) {
            $file = upload();
            $data['headimg'] = $file['headimg']['url'];
        }
        foreach ($data as $k => $v) {
            if ($v == '') {
                unset($data[$k]);
            }
        }
        Db::table('user')->where('id', $uid)->update($data);
        $msg['msg'] = '修改成功';
        return json($msg);
    }

    /**
     * *  司机进行认证服务
     **/
//    public function update_express()
//    {
//        $token = request()->request('token');
//        $data['uid'] = token_decode($token);
//        $data['idcard'] = request()->request('idcard');
//        $data['true_name'] = request()->request('true_name');
//        $user = Db::table('user')->where('id', $data['uid'])->find();
//        $data['bank_card'] = request()->request('bank_card');
//        $data['express_type'] = request()->request('express_type');
//        //$data['pid'] = $user['pid'];
//        //$data['cid'] = $user['cid'];
//        //$data['aid'] = $user['aid'];
//        $msg['state'] = 0;
//        $msg['data'] = '';
//        if (!$_FILES){
//            $msg['msg'] = '请上传手持身份证照片';
//        } else {
//            $bool = true;
//            foreach ($data as $k => $v) {
//                if (empty($v)) {
//                    $bool = false;
//                    $msg['msg'] = $k . ' not have';
//                    break;
//                }
//            }
//           if ($bool) {
//                $check = Db::table('express_check')->where('uid',$data['uid'])->order('id desc')->find();
//                if (count($check) > 0) {
//                    if ($check['status'] == 0) {
//                        $msg['msg'] = '您的申请已经在处理中，请耐心等待系统审核';
//                    }
//                } else {
//                    if ($check['status'] == 1) {
//                        $msg['msg'] = '您已经是司机了，请勿重复申请';
//                    } else {
//                        $msg['state'] = 1;
//                        $Files = upload();
//                        $data['idcardimg'] = $Files['idcardimg']['url'];
//                        $data['idcard_front'] = $Files['idcard_front']['url'];
//                        $data['idcard_verso'] = $Files['idcard_verso']['url'];
//                        $data['true_head_img'] = $Files['true_head_img']['url'];
//                        $data['status'] = 0;
//                        $data['retime'] = time();
//                        Db::table('express_check')->insert($data);
//                        $msg['msg'] = '申请成功，请等待审核';
//                    }
//                }
//            }
//        }
//        return json($msg);
//    }

    /**
     * * 获取物品分类
     **/
//    public function get_category()
//    {
//        $msg['state'] = 1;
//        $msg['data'] = Db::table('service_category')->field('id as cate_id,title,image')->where('gid', 0)->order('id asc')->select();
//        $msg['msg'] = '获取成功';
//        return json($msg);
//    }

    //扩大范围查询
    function big($lng, $lat, $scope, $type)
    {
        $pi = $this->get_lat_lng($scope);
        $this_time = time();
      //$count_sql = 'select count(id) from user where business=1 and isExpress=1 and active_time>'.($this_time-300).' and lat > '.$lat.'-'.$pi.' and lat < '.$lat.'+'.$pi.' and lng > '.$lng.'-'.$pi.' and lng < '.$lng.'+'.$pi.' order by ACOS(SIN(('.$lat.' * 3.1415) / 180 ) *SIN((lat * 3.1415) / 180 ) +COS(('.$lat.' * 3.1415) / 180 ) * COS((lat * 3.1415) / 180 ) *COS(('.$lng.'* 3.1415) / 180 - (lng * 3.1415) / 180 ) ) * 6380 asc';
        $type_sql = 'select express_type from express_type_order where order_type like \'%' . $type . '%\'';
        $count_sql = 'select count(id) from user where status=1 and business=1 and active_time>' . ($this_time - 300) . ' and isExpress=1 and express_type in(' . $type_sql . ') and lat > ' . $lat . '-' . $pi . ' and lat < ' . $lat . '+' . $pi . ' and lng > ' . $lng . '-' . $pi . ' and lng < ' . $lng . '+' . $pi . ' order by ACOS(SIN((' . $lat . ' * 3.1415) / 180 ) *SIN((lat * 3.1415) / 180 ) +COS((' . $lat . ' * 3.1415) / 180 ) * COS((lat * 3.1415) / 180 ) *COS((' . $lng . '* 3.1415) / 180 - (lng * 3.1415) / 180 ) ) * 6380 asc';
        $express = Db::table('user')->query($count_sql);
        return $express[0]['count(id)'];
    }
    /***
     计算跑腿费or行程间的费用：主要用于满足前台用户价格需求
    ****/

    //计算跑腿费or行程间的费用
    public function count_charge()
    {
        $area=request()->request('area');//
        $type=request()->request("type");//1
        $aid= Db::table('area')->where('name','like','%'.$area.'%')->value('id');
        if(empty($area)){
           $msg['state']=0;
           $msg['data']=(object)[]; 
           $msg['msg']="地区获取不到";
        }else{
        $data=Db::table("type_price")->field('price1,price2,price3,price4,price5')->where(['aid'=>$aid,'type'=>$type])->find();
        unset($area);
        $msg['state']=1; 
        $msg['data']=$data;
        $msg['msg']="success!";
        }
        return json($msg);
    }

//    //获取商品列表
//    public function get_goods()
//    {
//        $token = request()->request('token');
//        $uid = '';
//        if (!empty($token)) {
//            $uid = token_decode($token);
//        }
//        $area = request()->request('area');
//        $where['status'] = 0;
//        if (!empty($area)) {
//            $aid = Db::table('area')->where('name', 'like', '%' . $area . '%')->value('id');
//            $where['aid'] = $aid;
//        }
//        $cate_id = (int)request()->request('cate_id');
//        if (!empty($cate_id)) {
//            $where['cateid'] = $cate_id;
//        }
//        $msg['state'] = 1;
//        $page = request()->request('page') ? request()->request('page') : 1;
//        $pagesize = request()->request('pagesize') ? request()->request('pagesize') : 10;
//        $fields = 'id as goods_id,title,cateid,image1,image2,image3,image4,price,service';
//        $msg['data'] = Db::table('service')->field($fields)->where($where)->page($page, $pagesize)->select();
//        foreach ($msg['data'] as $k => $v) {
//            $number = Db::table('cart')->where(['uid' => $uid, 'goods_id' => $v['goods_id']])->value('number');
//            $msg['data'][$k]['cart_number'] = intval($number);
//        }
//        $msg['msg'] = '获取成功';
//        return json($msg);
//    }
     //用户获取拼车列表 user/get_pin_cate
     public function get_pin_cate(){
       $token=request()->request('token');
       $uid= token_decode($token);
       $area = request()->request('area');
       $aid= Db::table('area')->where('name','like','%'.$area.'%')->value('id');
       
      if(empty($token)||empty($area)){
          $msg['state']=0;
          $msg['msg']="error:数据错误!";
      }else{
        //本地区的拼车单user_pin:aid /to user:aid
        $page = request()->request('page') ? request()->request('page') : 1;
        $pagesize = request()->request('pagesize') ? request()->request('pagesize') :10;
        $fields='id as u_p_id,uid,total_count,price,place_name,aid,target_name,leave_time,count';
        $cate=Db::table("user_pin")->field($fields)->where(["status"=>["in","3,4,5,6,7"],'aid'=>$aid,'uid' => ['<>', $uid]])->page($page,$pagesize)->order('regtime desc')->select();
        foreach($cate as $k=>$v){
			$cate[$k]['uid']=$v['uid'];//司机uid
			$cate[$k]['total_count']=$v['total_count'];//拼单总人数
			$cate[$k]['count']=$v['count'];//现在拼车的人数
			//司机头像与司机的订单交易量
                        $cate[$k]['driver_phone']=Db::table('user')->where(['id'=>$cate[$k]['uid']])->value('phone');
			$express=Db::table("express_check")->where(['uid'=>$cate[$k]['uid'],'status'=>1])->find();
			$cate[$k]['headimg']=$express['true_head'];
			$cate[$k]['car_number']=$express['car_number'];
			$cate[$k]['name']=$express["true_name"];
			$cate[$k]['order_count']=Db::table('earning')->where('uid',$cate[$k]['uid'])->count();
			$cate[$k]['star']=5;//模拟一个star
			unset($cate[$k]['uid']);
			unset($cate[$k]['aid']);
		}
        $msg['state']=1;
        $msg['data']=$cate;
        $msg['msg']="success!";
       }
       return json($msg);
    }

    //获取支付信息
      public function get_pay_info(){
		$token = request()->request('token');
		$order_id = request()->request('order_id');
		$uid = token_decode($token);
		$ret['state'] = 0;
		$ret['msg'] = '';
		$ret['data'] = '';
		if(empty($uid) || empty($order_id)){
			$ret['msg'] = '参数错误';
		}else{
			$order = Db::table('order')->where(['order_id'=>$order_id])->find();
			if($order){
				if($order['status'] == 8){
					$ret['state'] = 1;
					$ret['data'] = $this->wxpay(['order_id'=>$order['order_id'],'price'=>$order['price']]);
					$ret['data']['order_id'] = $order['order_id'];
					$ret['data']['price'] = $order['price'];
					$ret['msg'] = '操作成功';
				}else{
					$ret['msg'] = '订单不能支付';
				}
			}else{
				$ret['msg'] = '没有此订单';
			}
		}
		return json($ret);
	}
 //计算
	public function Yester_unit_ttop($token = null, $sercer = null, $scope = null, $type = null)
	{
			$token = request()->request('token');
			$type = request()->request('type');
			$sercer = request()->request('sercer');
			$page = request()->request('page');
			$pagesize = request()->request('pagesize')?request()->request('pagesize'):10;
			$pi = $this->get_lat_lng($scope);
			$lng = request()->request('lng');
			$lat = request()->request('lat');
			$this_time = time();
			$type_sql = 'select express_type from express_type_order where order_type like \'%' . $type . '%\'';
			$count_sql = 'select count(id) from user where status=1 and business=1 and active_time>' . ($this_time - 300) . ' and isExpress=1 and express_type in(' . $type_sql . ') and lat > ' . $lat . '-' . $pi . ' and lat < ' . $lat . '+' . $pi . ' and lng > ' . $lng . '-' . $pi . ' and lng < ' . $lng . '+' . $pi . ' order by ACOS(SIN((' . $lat . ' * 3.1415) / 180 ) *SIN((lat * 3.1415) / 180 ) +COS((' . $lat . ' * 3.1415) / 180 ) * COS((lat * 3.1415) / 180 ) *COS((' . $lng . '* 3.1415) / 180 - (lng * 3.1415) / 180 ) ) * 6380 asc';
			$data = Db::table($type)->where($sercer)->page($page,$pagesize)->select();
			return json($data);
	}
//    //闪店下单
//    public function fast()
//    {
//        $token = request()->request('token');
//        $data = [];
//        $data['uid'] = token_decode($token);
//        $data['province'] = request()->request('province');
//        $data['city'] = request()->request('city');
//        $data['area'] = request()->request('area');
//        $data['target_lng'] = request()->request('target_lng');
//        $data['target_lat'] = request()->request('target_lat');
//        $data['target_phone'] = request()->request('target_phone');
//        $data['express_charge'] = request()->request('express_charge');
//        $bool = true;
//        $msg['state'] = 0;
//        $msg['data'] = [];
//        foreach ($data as $k => $v) {
//            if ($v == '' && substr($k, 0, 5) != 'place') {
//                $bool = false;
//                $msg['msg'] = $k . ' 不能为空';
//                break;
//            }
//        }
//        $data['target_address'] = request()->request('target_address');
//        $data['target_truename'] = request()->request('target_truename');
//        $data['remark'] = request()->request('remark');
//        $data['discount'] = request()->request('discount');
//        $data['tip'] = request()->request('tip');
//        $data['audio_length'] = request()->request('audio_length');
//        $price = 0;
//        $discount_money = 0;
//        if ($bool) {
//            $area = Db::table('area')->where('name', 'like', '%' . $data['area'] . '%')->find();
//            unset($data['area']);
//            if ($area['status'] == 0) {
//                $msg['msg'] = '抱歉，您所在的城市暂未开通服务';
//            } else {
//                if (!empty($data['discount'])) {
//                    $dis_check = Db::table('user_discounts')->where(['uid' => $data['uid'], 'id' => $data['discount'], 'flag' => 0])->find();
//                    if (count($dis_check) == 0) {
//                        die('error');
//                    } else {
//                        if ($dis_check['type'] == 'discount') {
//                            if ($data['express_charge'] >= $dis_check['full']) {
//                                $price = ($data['express_charge'] + $data['tip']) - $dis_check['minus'];
//                                $discount_money = $dis_check['minus'];
//                            }else{
//                                $price = $data['express_charge'] + $data['tip'];
//                            }
//                        }elseif ($dis_check['type'] == 'cash') {
//                            $price = ($data['express_charge'] + $data['tip']) - $dis_check['minus'];
//                            $discount_money = $dis_check['minus'];
//                        } elseif ($dis_check['type'] == 'reduced') {
//                            $price = ($data['express_charge'] + $data['tip']) * ($dis_check['minus'] / 10);
//                            $discount_money = $dis_check['minus'] / 10;
//                        }
//                        Db::table('user_discounts')->where(['uid' => $data['uid'], 'id' => $data['discount']])->update(['flag' => 1]);
//                    }
//                } else {
//                    $price = $data['express_charge'] + $data['tip'];
//                }
//                $data['price'] = $price;
//                $data['discount_money'] = $discount_money;
//                if ($_FILES) {
//                    if (!request()->request('mini')) {
//                        $Files = upload();
//                        foreach ($Files as $k => $v) {
//                            $data[$k] = $v['url'];
//                        }
//                    } else {
//                        $name = $_FILES['audio']['name'];
//                        $file_name = APP_PATH . 'cache/' . $name;
//                        move_uploaded_file($_FILES['audio']['tmp_name'], $file_name);
//                        $pcm_name = APP_PATH . 'cache/' . $name . '.pcm';
//                        $pcm = shell_exec(APP_PATH . 'silk_v3_decoder.exe ' . $file_name . ' ' . $pcm_name);
//                        @unlink($file_name);
//                        $mp3_name = APP_PATH . 'cache/' . $name . '.mp3';
//                        $mp3 = shell_exec(APP_PATH . 'ffmpeg.exe -y -f s16le -ar 24000 -ac 1 -i ' . $pcm_name . ' ' . $mp3_name);
//                        @unlink($pcm_name);
//                        $data['audio'] = $this->curl_silk_file($mp3_name);
//                        @unlink($mp3_name);
//                    }
//                }
//                $msg['state'] = 1;
//                $data['pid'] = Db::table('province')->where('name', 'like', '%' . $data['province'] . '%')->value('id');
//                unset($data['province']);
//                $data['cid'] = Db::table('city')->where('name', 'like', '%' . $data['city'] . '%')->value('id');
//                unset($data['city']);
//                $data['aid'] = $area['id'];
//                $IDENT = 'FA';
//                $data['order_id'] = $IDENT . date('ymdhis') . rand(1111, 9999);
//                $data['key'] = rand(100000, 999999);
//                $data['type'] = 'fast';
//                $data['issue_time'] = time();
//                $data['status'] = 1;
//                //商品列表，删除购物c
//                $goods_arr = Db::table('cart')->field('goods_id,number')->where('uid', $data['uid'])->select();
//                $price_all = 0;
//                foreach ($goods_arr as $k => $v) {
//                    $goods = Db::table('service')->where('id', $v['goods_id'])->find();
//                    $goods_info['order_id'] = strval($data['order_id']);
//                    $goods_info['goods_id'] = strval($v['goods_id']);
//                    $goods_info['number'] = strval($v['number']);
//                    $goods_info['price'] = strval($goods['price']);
//                    $price_all += $v['number'] * $goods['price'];
//                    Db::table('order_goods')->insert($goods_info);
//                }
//                $data['price'] = $data['express_charge'] + $price_all;
//                Db::table('cart')->where('uid', $data['uid'])->delete();
//                Db::table('order')->insert($data);
//                if (request()->request('mini')) {
//                    vendor("wxpay.WxPayApi");
//                    $order_id = $data['order_id'];
//                    $openid = request()->request('mini');
//                    $wxpay = new \WxPayApi();
//                    $back_url = \think\Url::build('mini_call_back', '', true, true);
//                    if (request()->request('wxd')) {
//                        $config = Db::table('wxpay')->where('type', 'wxd')->find();
//                    } else {
//                        $config = Db::table('wxpay')->where('type', 'mini')->find();
//                    }
//                    $result = $wxpay->config(['appid' => $config['appid'], 'mch_id' => $config['mchid'], 'key' => $config['key']], '跑帮郎付款', $back_url, $order_id, $data['price'] * 100, 'JSAPI', null, $openid);
//                    $msg['data'] = $result;
//                } else {
//                    $msg['data'] = $this->wxpay($data);
//                }
//                $msg['data']['order_id'] = $data['order_id'];
//                $msg['data']['price'] = $data['price'];
//                $msg['msg'] = '操作完成';
//            }
//        }
//        return json($msg);
//    }
    /**
     * *
     **/
//    public function shop_for_me()
//    {
//        $token = request()->request('token');
//        $data = [];
//        $data['uid'] = token_decode($token);
//        $data['province'] = request()->request('province');
//        $data['city'] = request()->request('city');
//        $data['area'] = request()->request('area');
//        $data['place_name'] = request()->request('place_name');
//        $data['place_lng'] = request()->request('place_lng');
//        $data['place_lat'] = request()->request('place_lat');
//        $data['target_name'] = request()->request('target_name');
//        $data['target_truename'] = request()->request('target_truename');
//        $data['target_lng'] = request()->request('target_lng');
//        $data['target_lat'] = request()->request('target_lat');
//        $data['target_phone'] = request()->request('target_phone');
//        $data['express_charge'] = request()->request('express_charge');
//        $bool = true;
//        $msg['state'] = 0;
//        $msg['data'] = [];
//        foreach ($data as $k => $v){
//            if ($v == '' && substr($k, 0, 5) != 'place') {
//                $bool = false;
//                $msg['msg'] = $k . ' 不能为空';
//                break;
//            }
//        }
//        $data['cate_id'] = (int)request()->request('cate_id');
//        $data['place_address'] = request()->request('place_address');
//        $data['target_address'] = request()->request('target_address');
//        $data['require_time'] = request()->request('require_time');
//        $data['remark'] = request()->request('remark');
//        $data['discount'] = request()->request('discount');
//        $data['audio_length'] = request()->request('audio_length');
//        $data['tip'] = request()->request('tip');
//        $price = 0;
//        $discount_money = 0;
//        if ($bool) {
//            $area = Db::table('area')->where('name', 'like', '%' . $data['area'] . '%')->find();
//            unset($data['area']);
//            if ($area['status'] == 0) {
//                $msg['msg'] = '抱歉，您所在的城市暂未开通服务';
//            } else {
//                if (!empty($data['discount'])) {
//                    $dis_check = Db::table('user_discounts')->where(['uid' => $data['uid'], 'id' => $data['discount'], 'flag' => 0])->find();
//                    if (count($dis_check) == 0) {
//                        die('error');
//                    } else {
//                        if ($dis_check['type'] == 'discount') {
//                            if ($data['express_charge'] >= $dis_check['full']){
//                                $discount_money = $dis_check['minus'];
//                                $price = ($data['express_charge'] + $data['tip']) - $discount_money;
//                            } else {
//                                $price = $data['express_charge'] + $data['tip'];
//                            }
//                        } elseif ($dis_check['type'] == 'cash') {
//                            $discount_money = $dis_check['minus'];
//                            $price = ($data['express_charge'] + $data['tip']) - $discount_money;
//                        } elseif ($dis_check['type'] == 'reduced') {
//                            $discount_money = $dis_check['minus'] / 10;
//                            $price = ($data['express_charge'] + $data['tip']) * $discount_money;
//                        }
//                        Db::table('user_discounts')->where(['uid' => $data['uid'], 'id' => $data['discount']])->update(['flag' => 1]);
//                    }
//                } else {
//                    $price = $data['express_charge'] + $data['tip'];
//                }
//                $data['price'] = $price;
//                $data['discount_money'] = $discount_money;
//                if ($data['price'] <= 0) {
//                    $data['price'] = '0.01';
//                }
//                if ($_FILES) {
//                    if (!request()->request('mini')) {
//                        $Files = upload();
//                        foreach ($Files as $k => $v) {
//                            $data[$k] = $v['url'];
//                        }
//                    }else{
//                        $name = $_FILES['audio']['name'];
//                        $file_name = APP_PATH . 'cache/' . $name;
//                        move_uploaded_file($_FILES['audio']['tmp_name'], $file_name);
//                        $pcm_name = APP_PATH . 'cache/' . $name . '.pcm';
//                        $pcm = shell_exec(APP_PATH . 'silk_v3_decoder.exe ' . $file_name . ' ' . $pcm_name);
//                        @unlink($file_name);
//                        $mp3_name = APP_PATH . 'cache/' . $name . '.mp3';
//                        $mp3 = shell_exec(APP_PATH . 'ffmpeg.exe -y -f s16le -ar 24000 -ac 1 -i ' . $pcm_name . ' ' . $mp3_name);
//                        @unlink($pcm_name);
//                        $data['audio'] = $this->curl_silk_file($mp3_name);
//                        @unlink($mp3_name);
//                    }
//                }
//                $msg['state'] = 1;
//                $data['pid'] = Db::table('province')->where('name', 'like', '%' . $data['province'] . '%')->value('id');
//                unset($data['province']);
//                $data['cid'] = Db::table('city')->where('name', 'like', '%' . $data['city'] . '%')->value('id');
//                unset($data['city']);
//                $data['aid'] = $area['id'];
//                $IDENT = 'SH';
//                $data['order_id'] = $IDENT . date('ymdhis') . rand(1111, 9999);
//                $data['key'] = rand(100000, 999999);
//                $data['type'] = 'shop_for_me';
//                $data['issue_time'] = time();
//                $data['status'] = 1;
//                Db::table('order')->insert($data);
//                if (request()->request('mini')) {
//                    vendor("wxpay.WxPayApi");
//                    $order_id = $data['order_id'];
//                    $openid = request()->request('mini');
//                    $wxpay = new \WxPayApi();
//                    $back_url = \think\Url::build('mini_call_back', '', true, true);
//                    if (request()->request('wxd')) {
//                        $config = Db::table('wxpay')->where('type', 'wxd')->find();
//                    } else {
//                        $config = Db::table('wxpay')->where('type', 'mini')->find();
//                    }
//                    $result = $wxpay->config(['appid' => $config['appid'], 'mch_id' => $config['mchid'], 'key' => $config['key']], '跑帮郎付款', $back_url, $order_id, $data['price'] * 100, 'JSAPI', null, $openid);
//                    $msg['data'] = $result;
//                } else {
//                    $msg['data'] = $this->wxpay($data);
//                }
//                $msg['data']['order_id'] = $data['order_id'];
//                $msg['data']['price'] = $data['price'];
//                $msg['msg'] = '操作完成';
//            }
//        }
//        return json($msg);
//    }


    public function curl_upload()
    {
        $info = upload();
        return $info['files']['url'];
    }

    public function curl_silk_file($silk)
    {
        // 创建一个 cURL 句柄
        $ch = curl_init($_SERVER['HTTP_HOST'] . url('user/curl_upload'));

        // 创建一个 CURLFile 对象
        $file = curl_file_create($silk, 'audio/mp3', 'test');

        // 设置 POST 数据
        $data = array('files' => $file);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Opera/9.80 (Windows NT 6.2; Win64; x64) Presto/2.12.388 Version/12.15');
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: multipart/form-data'));

        // 执行句柄
        return curl_exec($ch);
    }

    /**
     * * 跑个腿 user/run_for_you
     **/
    public function run_for_you()
    {
        $token = request()->request('token');
        $data = [];
        $data['uid'] = token_decode($token);
        $data['province'] = request()->request('province');
        $data['city'] = request()->request('city');
        $data['area'] = request()->request('area');
        $data['audio_length'] = request()->request('audio_length');//音频长度
        $data['place_truename'] = request()->request('place_truename');//联系人
        $data['place_phone'] = request()->request('place_phone');
        $data['place_address'] = request()->request('place_address');//取货地址
        $data['place_lng'] = request()->request('place_lng');//经度
        $data['place_lat'] = request()->request('place_lat');//纬度
        $data['target_address'] = request()->request('target_address');//送货地址
        $data['target_lng'] = request()->request('target_lng');//经度
        $data['target_lat'] = request()->request('target_lat');//纬度
        $data['place_area']=request()->request('place_area');
        $data['target_area']=request()->request('target_area');
        $bool = true;
        $msg['state'] = 0;
        $msg['data'] = [];
        foreach ($data as $k => $v) {
            if ($v ===''){
                $bool = false;
                $msg['msg'] = $k . ' 不能为空';
                break;
            }
        }
        $data['require_time']=time();//下单时间
        $data['tip'] = request()->request('tip');//小费
      //$data['discount_id'] = request()->request('discount_id');// 
        if($bool){
           $area = Db::table('area')->where('name', 'like', '%' . $data['area'] . '%')->find();
           unset($data['area']);
           if ($area['status'] == 0){
                $msg['msg'] = '抱歉，您所在的城市暂未开通服务';
           }else{
           $order_count=Db::table("order")->where(['uid'=>$data['uid'],'type'=>'run_for_you','status'=>['in','1,3,4,5,6,7,8']])->count();
           if($order_count){
             $msg['data']="";
             $msg['state']=0;
             $msg['msg']="当前有订单在进行,请完成订单后再下单";
           }else{
               
                $data['express_charge']=0;
                 //照片和语音
                if($_FILES){
                    if (!request()->request('mini')){
                        $Files = upload();
                        foreach ($Files as $k => $v) {
                            $data[$k] = $v['url'];//files
                        }
                     }else{
                        $name = $_FILES['audio']['name'];
                        $file_name = APP_PATH . 'cache/' . $name;
                        move_uploaded_file($_FILES['audio']['tmp_name'], $file_name);
                        $pcm_name = APP_PATH . 'cache/' . $name . '.pcm';
                        $pcm = shell_exec(APP_PATH . 'silk_v3_decoder.exe ' . $file_name . ' ' . $pcm_name);
                        @unlink($file_name);
                        $mp3_name = APP_PATH . 'cache/' . $name . '.mp3';
                        $mp3 = shell_exec(APP_PATH . 'ffmpeg.exe -y -f s16le -ar 24000 -ac 1 -i ' . $pcm_name . ' ' . $mp3_name);
                        @unlink($pcm_name);
                        $data['audio'] = $this->curl_silk_file($mp3_name);
                        @unlink($mp3_name);
                    }
                }
                $msg['state'] = 1;
                $data['pid'] = Db::table('province')->where('name', 'like', '%' . $data['province'] . '%')->value('id');
                unset($data['province']);
                $data['cid'] = Db::table('city')->where('name', 'like', '%' . $data['city'] . '%')->value('id');
                unset($data['city']);
                $data['aid'] = $area['id'];
                $data['type'] ='run_for_you';
                $IDENT = 'RFY';
                $data['order_id'] = $IDENT . date('ymdhis') . rand(1111, 9999);
                
                $data['status'] = 1;
                Db::table('order')->insert($data);
                $msg['data'] = $data['order_id'];
                $msg['msg'] = '操作完成';
             if (!empty($data['place_lat']) && !empty($data['place_lng'])){
                    $lng = $data['place_lng'];
                    $lat = $data['place_lat'];
               }else{
                    $lng = $data['target_lng'];
                    $lat = $data['target_lat'];
               }
	      //推送附近司机
                $min_size = 0;
                $express_config = Db::table('express_config')->where('aid', $data['aid'])->find();
                $scope = $express_config['scope'];
                $big_scope = $scope * 2;
                $result_scope = $min_size;
                while($scope <= $big_scope && $result_scope == $min_size) {
                    $result_scope = $this->big($lng, $lat, $scope, $data['type']);
                    $scope++;
                }
	        // var_dump($result_scope);exit;
                if($result_scope <= $min_size) {
                    $msg['msg'] = '附近暂无车辆';
                 }elseif($result_scope > $min_size){
                    $pi = $this->get_lat_lng($scope);
                    $msg['state'] = 1;
                    $this_time = time();
                    $type_sql = 'select express_type from express_type_order where order_type like \'%' . $data['type'] . '%\'';
                    $express_sql = 'select id from user where status=1 and business=1 and active_time>' . ($this_time - 300) . ' and isExpress=1 and express_type in(' . $type_sql . ') and lat > ' . $lat . '-' . $pi . ' and lat < ' . $lat . '+' . $pi . ' and lng > ' . $lng . '-' . $pi . ' and lng < ' . $lng . '+' . $pi . ' order by ACOS(SIN((' . $lat . ' * 3.1415) / 180 ) *SIN((lat * 3.1415) / 180 ) +COS((' . $lat . ' * 3.1415) / 180 ) * COS((lat * 3.1415) / 180 ) *COS((' . $lng . '* 3.1415) / 180 - (lng * 3.1415) / 180 ) ) * 6380 asc';
                    $express = Db::table('user')->query($express_sql);
                    $express_array = [];
                    foreach ($express as $v) {
                       $express_array[] = md5($v['id']);
                    }
                    push($express_array, json_encode(['type' => 2, 'message' => '附近有新订单啦~', 'parameters' => $data['order_id'], 'status' => 4]));
                    $msg['msg'] = '操作成功';
                }
             }
          }

       }
        return json($msg);
     }
     
     //用户所在地区的价格
     public function get_room_price()
    {
       $area=request()->request("area");
       $aid= Db::table('area')->where('name','like','%'.$area.'%')->value('id');
       if(empty($area)||empty($aid)){
         $msg['state']=0;
         $msg['data']="";
         $msg['msg']="获取不到当前位置";
        }else{
         $msg['state']=1;
         $room_price=Db::table("type_price")->where(['aid'=>$aid,'type'=>3])->value("price1");
         $msg['data']=$room_price;
         $msg['msg']="success";
       }
       return json($msg);  
     }
     
      /**
       * 订个房
       * 用户端直接提交并支付订单
       * ***/
     public function book_a_room()
    {
        $token=request()->request("token");
        $data['uid']=token_decode($token);
        $data['province']=request()->request("province");//省province
        $data['city']=request()->request("city");//城市 city
        $data['area']=request()->request("area");//地区 area
        $data['place_truename']=request()->request("place_truename");//联系人 place_truename
        $data['place_phone']=request()->request("place_phone");//手机号 place_phone
        $data['place_address']=request()->request("place_address");//当前地址
        $data['place_lat'] = request()->request('place_lat');//纬度 place_lat用户当前地点的纬度
        $data['place_lng'] = request()->request('place_lng');//经度 place_lng用户当前地点的经度
        $data['audio_length'] = request()->request('audio_length');//音频长度
        $data['place_area']=request()->request('place_area');
        $data['target_area']=request()->request('target_area');
        //$lng = $data['place_lng'];
        //$lat = $data['place_lat'];
        $bool = true;
        $msg['state'] = 0;
        $msg['data'] = [];
        foreach ($data as $k => $v) {
            if ($v == '') {
                $bool = false;
                $msg['msg'] = $k . ' 不能为空';
                break;
            }
        }

    $area=Db::table("area")->where("name","like",'%'.$data['area'].'%')->find(); //地区
    unset($data['area']);
    $data['aid']=$area['id'];
    //var_dump($data['aid']);exit();
    if($bool){
        //优惠券和价格
         $data['discount_id']=request()->request("discount_id");
         $data['express_charge']=Db::table("type_price")->where(['aid'=>$data['aid'],'type'=>3])->value("price1");
        if(empty($data['discount_id'])){
          $data['price']=$data['express_charge'];//用户要付的金额
          $data['express_get_money']=$data['express_charge'];//酒店得到的金钱
        }else{
        $data['discount_money']=Db::table("user_discounts")->where(['id'=>$data['discount_id'],'uid'=>$data['uid'],'status'=>1])->value("minus");  //优惠券金额
        $data['price']=$data['express_charge']-$data['discount_money'];//订单要付的钱
        $data['express_get_money']=$data['express_charge'];//酒店得到的金钱
        }
            if($area['status']==0){
                $msg['msg']="抱歉，您所在的城市未开通服务";
           }else{
            $order_count=Db::table("order")->where(["uid"=>$data['uid'],"type"=>"book_a_room","status"=>["in",'1,3,7,8']])->count();
            if($order_count){
            $msg['state']=0;
            $msg['data']=(object)[];
            $msg['msg']="当前有订单在进行,请完成后下单";
            }else{ 
                
                //图片和音频
                if($_FILES){
                    if (!request()->request('mini')){
                        $Files = upload();
                        foreach ($Files as $k => $v) {
                            $data[$k] = $v['url'];//files
                        }
                     }else{
                        $name = $_FILES['audio']['name'];
                        $file_name = APP_PATH . 'cache/' . $name;
                        move_uploaded_file($_FILES['audio']['tmp_name'], $file_name);
                        $pcm_name = APP_PATH . 'cache/' . $name . '.pcm';
                        $pcm = shell_exec(APP_PATH . 'silk_v3_decoder.exe ' . $file_name . ' ' . $pcm_name);
                        @unlink($file_name);
                        $mp3_name = APP_PATH . 'cache/' . $name . '.mp3';
                        $mp3 = shell_exec(APP_PATH . 'ffmpeg.exe -y -f s16le -ar 24000 -ac 1 -i ' . $pcm_name . ' ' . $mp3_name);
                        @unlink($pcm_name);
                        $data['audio'] = $this->curl_silk_file($mp3_name);
                        @unlink($mp3_name);
                    }
                }  
                $msg['state']=1;
                $data['require_time']=time();//下单时间:regtime
                $data['pid']=Db::table("province")->where("name","like",'%'.$data['province'].'%')->value("id");
                unset($data['province']);
                $data['cid']=Db::table("city")->where('name',"like",'%'.$data['city'].'%')->value('id');
                unset($data['city']);
                $data['type']="book_a_room";
                $IDENT="BAR";
                $data['order_id']=$IDENT.date('ymdhis').rand(1111,9999);
                $data['status']=8;//生成新订单
                $id=Db::table("order")->insertGetId($data);//new order_id
                $order=Db::table("order")->field("order_id,price,status")->where("id",$id)->find();
                if($order['status']==8){
                 $IDENT = substr($order['order_id'], 0, 3);
                 $new_id = $IDENT . date('ymdhis') .rand(1111, 9999);
                 Db::table('order')->where('order_id', $order['order_id'])->update(['order_id' =>$new_id]);
                 $order['order_id'] =$new_id;
                 $data=$this->wxpay($order);
                // dump($data);exit;小心赋值被覆盖
                 $data['order_id']=$order['order_id'];
                 $data['price']=$order["price"];
                 $msg['data']=$data;
                }
                $msg['msg']="success";
               
             }
           }
        }
        return json($msg);
   }

     /**叫个车    call_the_car
     * ***/
    public function call_the_car()
    {
        $token=request()->request("token");//token
        $uid= token_decode($token);
        $data['uid']=$uid;//用户的uid
        $data['province']=request()->request("province");//省province
        $data['city']=request()->request("city");//城市 city
        $data['area']=request()->request("area");//地区 area
        $data['place_truename']=request()->request("place_truename");//联系人 place_truename
        $data['place_phone']=request()->request("place_phone");//手机号 place_phone
        $data['place_address']=request()->request("place_address");//上车地点 place_address
        $data['place_lat'] = request()->request('place_lat');//纬度 place_lat用户上车地点的纬度
        $data['place_lng'] = request()->request('place_lng');//经度 place_lng用户上车地点的经度
        $data['target_address']=request()->request("target_address");//要去的地点 target_address
        $data['target_lng'] = request()->request('target_lng');//要去地区的经度
        $data['target_lat'] = request()->request('target_lat');//要去地区的纬度
        $data['place_area']= request()->request('place_area');//
        $data['target_area']=request()->request('target_area');//
        $data['tip'] = request()->request("tip");//小费
        $data['audio_length'] = request()->request('audio_length');
        $data['require_time'] = time();//下单时间
        $bool = true;
        foreach ($data as $k => $v){
            if ($v == '') {
                $bool = false;
                $msg['msg'] = $k . ' 不能为空';
                break;
            }
        }
        $data['price']=0;
        $msg['state']=0;
      //$data['discount_id']=request()->request('discount_id');  
        if($bool){
         $area=Db::table("area")->where("name","like",'%'.$data['area'].'%')->find();
         unset($data['area']);
         if($area['status']==0){
               $msg['msg']="很抱歉,您所在的城市未开通服务";
         }else{
           $order_count=Db::table("order")->where(['uid'=>$data['uid'],'type'=>'call_the_car','status'=>['in',"1,3,4,5,6,7,8"]])->count();
           if($order_count){
           $msg['data']="";
           $msg['state']=0;
           $msg['msg']="请完成当前订单后，再下新单";
           }else{
                 $data['express_charge']=0;
                 //录音和照片
                 if($_FILES){
                    if (!request()->request('mini')){
                        $Files = upload();//照片
                        foreach ($Files as $k => $v) {
                            $data[$k] = $v['url'];
                        }
                    }else{
                        $name = $_FILES['audio']['name'];
                        $file_name = APP_PATH . 'cache/' . $name;
                        move_uploaded_file($_FILES['audio']['tmp_name'], $file_name);
                        $pcm_name = APP_PATH . 'cache/' . $name . '.pcm';
                        $pcm = shell_exec(APP_PATH . 'silk_v3_decoder.exe ' . $file_name . ' ' . $pcm_name);
                        @unlink($file_name);
                        $mp3_name = APP_PATH . 'cache/' . $name . '.mp3';
                        $mp3 = shell_exec(APP_PATH . 'ffmpeg.exe -y -f s16le -ar 24000 -ac 1 -i ' . $pcm_name . ' ' . $mp3_name);
                        @unlink($pcm_name);
                        $data['audio'] = $this->curl_silk_file($mp3_name);
                        @unlink($mp3_name);
                    }
                }
                $msg['state'] = 1;
                $data['pid'] = Db::table('province')->where('name', 'like', '%' . $data['province'] . '%')->value('id');
                unset($data['province']);
                $data['cid'] = Db::table('city')->where('name', 'like', '%' . $data['city'] . '%')->value('id');
                unset($data['city']);
                $data['aid'] = $area['id'];
                $data['type']="call_the_car";//订单的类别
                $IDENT="CTC";//order_id前缀
                $data['order_id']=$IDENT.date('ymdhis').rand(1111,9999);
                $data['status']=1;//生成新订单
                Db::table("order")->insert($data);
                $msg['data']= $data['order_id'];
               
	       if (!empty($data['place_lat']) && !empty($data['place_lng'])) {
                    $lng = $data['place_lng'];
                    $lat = $data['place_lat'];
                }else{
                    $lng = $data['target_lng'];
                    $lat = $data['target_lat'];
                }

	     //推送附近司机
                $min_size = 0;
                $express_config = Db::table('express_config')->where('aid', $data['aid'])->find();
                $scope = $express_config['scope'];
                $big_scope = $scope * 2;
                $result_scope = $min_size;
                while($scope <= $big_scope && $result_scope == $min_size) {
                    $result_scope = $this->big($lng, $lat, $scope, $data['type']);
                    $scope++;
                }
	        // var_dump($result_scope);exit;
                if($result_scope <= $min_size) {
                    $msg['msg'] = '附近暂无车辆';
                  }elseif($result_scope > $min_size){
                    $pi = $this->get_lat_lng($scope);
                    $msg['state'] = 1;
                    $this_time = time();
                    $type_sql = 'select express_type from express_type_order where order_type like \'%' . $data['type'] . '%\'';
                    $express_sql = 'select id from user where status=1 and business=1 and active_time>' . ($this_time - 300) . ' and isExpress=1 and express_type in(' . $type_sql . ') and lat > ' . $lat . '-' . $pi . ' and lat < ' . $lat . '+' . $pi . ' and lng > ' . $lng . '-' . $pi . ' and lng < ' . $lng . '+' . $pi . ' order by ACOS(SIN((' . $lat . ' * 3.1415) / 180 ) *SIN((lat * 3.1415) / 180 ) +COS((' . $lat . ' * 3.1415) / 180 ) * COS((lat * 3.1415) / 180 ) *COS((' . $lng . '* 3.1415) / 180 - (lng * 3.1415) / 180 ) ) * 6380 asc';
                    $express = Db::table('user')->query($express_sql);
                    $express_array = [];
                    foreach ($express as $v){
                        $express_array[] = md5($v['id']);
                    }
                    push($express_array, json_encode(['type' => 2, 'message' => '附近有新订单啦~', 'parameters' => $data['order_id'], 'status' => 4]));
                    $msg['msg'] = '操作成功';
                }
           }
         }
       }
        return json($msg);
    }
     //获取接单司机的状态和头像  user/get_grab_driver:
     public function get_grab_driver(){
      $token=request()->request("token");   //用户提供uid 和order_id
      $uid= token_decode($token);//用户
      $order_id=request()->request("order_id");//由用户在产生订单后返回的一个订单编号
      $cate=[];
      if(empty($order_id)){
         $msg['state']=0;
         $msg['msg']="订单号error";
      }else{
       $express=Db::table("order")->where(["order_id"=>$order_id,'uid'=>$uid,'status'=>3])->value("express");
       $cate=Db::table("express_check")->field("true_name,true_head,car_number")->where('uid',$express)->find();
       $cate['phone']=Db::table("user")->field("phone")->where('id',$express)->value("phone");//司机手机
       $cate['order_count']=Db::table('earning')->where('uid',$express)->count();//订单数
       $cate['star']=5;//模拟一个star
       //$cate['driver_id']=$express;//获取司机经纬度时用到
       $msg['state']=1;
       $msg['data']=$cate;
       $msg['msg']="success!";
      }
      return json($msg);
    }
//    //获取司机的经纬度
    public function get_driver_lat_lng(){
     $driver_id=request()->request("driver_id");//
     $cate=Db::table("user")->field("lat,lng")->where('id',$driver_id)->find(); //
     if($cate){
		 $msg['state'] = 1;
		 $msg['data'] = $cate;
		 $msg['msg'] = '获取成功';
	 }else{
		 $msg['state'] = 0;
		 $msg['data'] = $cate;
		 $msg['msg'] = '获取失败';
	 }
	 return json($msg);
     }


    /**
     * * 帮忙
     **/
//    public function help()
//    {
//        $token = request()->request('token');
//        $data = [];
//        $data['uid'] = token_decode($token);
//        $data['province'] = request()->request('province');
//        $data['city'] = request()->request('city');
//        $data['area'] = request()->request('area');
//        $data['target_name'] = request()->request('target_name');
//        $data['target_lng'] = request()->request('target_lng');
//        $data['target_lat'] = request()->request('target_lat');
//        $data['target_phone'] = request()->request('target_phone');
//        $data['target_truename'] = request()->request('target_truename');
//        $data['express_charge'] = request()->request('express_charge');
//        $bool = true;
//        foreach ($data as $k => $v){
//            if ($v == '') {
//                $bool = false;
//                $msg['msg'] = $k . ' 不能为空';
//                break;
//            }
//        }
//        $data['cate_id'] = (int)request()->request('cate_id');
//        $data['remark'] = request()->request('remark');
//        $data['flag'] = request()->request('flag') ? request()->request('flag') : 0;
//        $data['audio_length'] = request()->request('audio_length');
//        $data['require_time'] = request()->request('require_time');
//        $data['tip'] = request()->request('tip');
//        $data['price'] = $data['tip'] + $data['express_charge'];
//        $data['target_address'] = request()->request('target_address');
//        $data['discount'] = request()->request('discount');
//        $msg['state'] = 0;
//        $msg['data'] = [];
//        $price = 0;
//        $discount_money = 0;
//        if ($bool){
//            $area = Db::table('area')->where('name', 'like', '%' . $data['area'] . '%')->find();
//            unset($data['area']);
//            if ($area['status'] == 0) {
//                $msg['msg'] = '抱歉，您所在的城市暂未开通服务';
//            }else {
//                if (!empty($data['discount'])) {
//                    $dis_check = Db::table('user_discounts')->where(['uid' => $data['uid'], 'id' => $data['discount'], 'flag' => 0])->find();
//                    if (count($dis_check) == 0) {
//                        die('error');
//                    }else{
//                        if ($dis_check['type'] == 'discount') {
//                            if ($data['express_charge'] >= $dis_check['full']) {
//                                $price = ($data['express_charge'] + $data['tip']) - $dis_check['minus'];
//                                $discount_money = $dis_check['minus'];
//                            } else {
//                                $price = $data['express_charge'] + $data['tip'];
//                            }
//                        } elseif ($dis_check['type'] == 'cash') {
//                            $price = ($data['express_charge'] + $data['tip']) - $dis_check['minus'];
//                            $discount_money = $dis_check['minus'];
//                        } elseif ($dis_check['type'] == 'reduced') {
//                            $price = ($data['express_charge'] + $data['tip']) * ($dis_check['minus'] / 10);
//                            $discount_money = $dis_check['minus'] / 10;
//                        }
//                        Db::table('user_discounts')->where(['uid' => $data['uid'], 'id' => $data['discount']])->update(['flag' => 1]);
//                    }
//                }else {
//                    $price = $data['express_charge'] + $data['tip'];
//                }
//                $data['price'] = $price;
//                $data['discount_money'] = $discount_money;
//                if($_FILES){
//                    if (!request()->request('mini')) {
//                        $Files = upload();
//                        foreach ($Files as $k => $v) {
//                            $data[$k] = $v['url'];
//                        }
//                    } else {
//                        $name = $_FILES['audio']['name'];
//                        $file_name = APP_PATH . 'cache/' . $name;
//                        move_uploaded_file($_FILES['audio']['tmp_name'], $file_name);
//                        $pcm_name = APP_PATH . 'cache/' . $name . '.pcm';
//                        $pcm = shell_exec(APP_PATH . 'silk_v3_decoder.exe ' . $file_name . ' ' . $pcm_name);
//                        @unlink($file_name);
//                        $mp3_name = APP_PATH . 'cache/' . $name . '.mp3';
//                        $mp3 = shell_exec(APP_PATH . 'ffmpeg.exe -y -f s16le -ar 24000 -ac 1 -i ' . $pcm_name . ' ' . $mp3_name);
//                        @unlink($pcm_name);
//                        $data['audio'] = $this->curl_silk_file($mp3_name);
//                        @unlink($mp3_name);
//                    }
//                }
//                $msg['state'] = 1;
//                $data['pid'] = Db::table('province')->where('name', 'like', '%' . $data['province'] . '%')->value('id');
//                unset($data['province']);
//                $data['cid'] = Db::table('city')->where('name', 'like', '%' . $data['city'] . '%')->value('id');
//                unset($data['city']);
//                $data['aid'] = $area['id'];
//                if(empty($data['flag'])){
//                    $data['type'] = 'help';
//                    $IDENT = 'HE';
//                } else {
//                    $data['type'] = 'anxious';
//                    $IDENT = 'AN';
//                }
//                $data['order_id'] = $IDENT . date('ymdhis') . rand(1111, 9999);
//                $data['key'] = rand(100000, 999999);
//                $data['issue_time'] = time();
//                $data['status'] = 1;
//                Db::table('order')->insert($data);
//                $msg['data']['order_id'] = $data['order_id'];
//              //  $msg['data']['price'] = $data['price'];
//                $msg['msg'] = '操作完成';
//            }
//        }
//        return json($msg);
//    }

    /***用户加入拼车订单(insert)***/
    public function pin_cart(){
      $token=request()->request('token');     
      $data['uid']= token_decode($token);//uid
      $data['u_p_id']=request()->request('u_p_id');//u_p_id
      $order_express_charge=request()->request('express_charge');//司机单价
      $data['count']=request()->request('count');//订单所乘坐的人数
      $data['place_truename']=request()->request("place_truename");//乘坐人
      $data['place_phone']=request()->request("place_phone");//联系手机
      $data['receive_time']=request()->request("require_time");//上车时间
      $data['place_address']=request()->request('place_address');//上车地点
      $data['place_lat']=request()->request("place_lat");//用户上车地址纬度
      $data['place_lng']=request()->request("place_lng");//用户上车地址经度
      $data['province'] = request()->request('province');//省
      $data['city'] = request()->request('city');//市
      $data['area'] = request()->request('area');//县
      $data['place_area']=request()->request('place_area');//下单所在地区
      $data['target_area']=request()->request('target_area');//下单所传区域
      $bool = true;
      foreach ($data as $k => $v){
          if ($v == '') {
                $bool = false;
                $msg['state']=0;
                $msg['data']="";
                $msg['msg'] = $k . '不能为空';
                break;
            }
     }
     //订单要付的价格相关
     $data['discount_id']=request()->request("discount_id");//下单优惠券_id
     if(empty($data['discount_id'])){
        $data['price']=$data['count']*$order_express_charge;//拼车要付的金额
        $data['express_charge']=$data['count']*$order_express_charge;
        $data['express_get_money']=$data['count']*$order_express_charge;//司机得到的金钱
      }else{
       $data['discount_money']=Db::table("user_discounts")->where(['id'=>$data['discount_id'],'uid'=>$data['uid'],'status'=>1])->value("minus");  //优惠券金额
       $data['price']=$data['count']*$order_express_charge-$data['discount_money'];//订单要付的钱
       $data['express_charge']=$data['count']*$order_express_charge;
       $data['express_get_money']=$data['count']*$order_express_charge;//司机得到的金钱
     }
    if($bool){
             $area = Db::table('area')->where('name', 'like', '%' . $data['area'] . '%')->find();
              unset($data['area']);
              if ($area['status'] == 0){
                  $msg['msg'] = '抱歉，您所在的城市暂未开通服务';
            }else{
             //加入拼车后不能再加入别的拼车,一直到订单完成
             $order_count=Db::table("order")->where(['uid'=>$data['uid'],'type'=>'user_pin_car','status'=>['in','3,4,5,6,7,8']])->count();
             if($order_count){
               $msg['data']=(object)[];
               $msg['state']=0;
               $msg['msg']="当前有订单在进行,请完成订单后再下单";
             }else{
                $check=Db::table("user_pin")->where("id",$data['u_p_id'])->find();
                $driver_data=Db::table("user")->field("phone,true_name")->where("id",$check['uid'])->find();
                if($check['count']>$check['total_count']){
                    $msg['state']=0;
                    $msg['data']=(object)[];
                    $msg['msg']="error:数据出错";
                }elseif($check['count']==$check['total_count']){
                    $msg['state']=0;
                    $msg['data']=(object)[];
                    $msg['msg']="抱歉，拼车人数已满";
                }else{
                 $msg['state'] = 1;
                 $data['require_time']=time();//下单时间
                 $data['target_truename']=$driver_data["true_name"];
                 $data['target_phone']=$driver_data["phone"];
                 $data['place_name']=$check['place_name'];//出发地点
                 $data['issue_time']=$check['leave_time'];//出发时间
                 $data['target_name']=$check['target_name'];//要去的地方
                 $data['express']=$check['uid'];//司机id的信息
                 $data['pid'] = Db::table('province')->where('name', 'like', '%' . $data['province'] . '%')->value('id');
                 unset($data['province']);
                 $data['cid'] = Db::table('city')->where('name', 'like', '%' . $data['city'] . '%')->value('id');
                 unset($data['city']);
                 $data['aid'] = $area['id'];
                 $data['type'] = 'user_pin_car';
                 $IDENT = 'PIN';
                 $data['order_id'] = $IDENT . date('ymdhis') . rand(1111, 9999);
                 $data['ident']=$IDENT;
                 $data['status'] = 8;//待支付
                 $id=Db::table('order')->insertGetId($data);//生成拼车的订单
                 $order=Db::table("order")->field("order_id,express,price,status")->where("id",$id)->find();
                 push(md5($order['express']), json_encode(['type' =>2, 'message' => '用户已加入拼车', 'parameters' =>$order["order_id"], 'status' =>16]));
                 insert_message($order['express'], '加入拼车', '用户加入拼车', '16', $order['order_id']);
                 $msg['state']=1;
                 if($order['status']==8){
                 $IDENT = substr($order['order_id'], 0, 3);
                 $new_id = $IDENT . date('ymdhis') .rand(1111, 9999);
                 Db::table('order')->where('order_id', $order['order_id'])->update(['order_id' => $new_id]);
                 $order['order_id'] = $new_id;
                 $data=$this->wxpay($order);
                 $data['order_id']=$order['order_id'];
                 $data['price']=$order["price"];
                 $msg['data']=$data;
                 $msg['msg']="success";
                }
                $msg['msg'] = '操作完成';
               }
             }
           }
        }
       return json($msg);
    }
     /**
      * 1 用户退出拼车即删除订单表中的一切数据
      * 2 在司机没有接到用户之前均可退出
      * 3用户退出拼车即删除订单，更新拼车表中count数值
      */
//    public function abandon_pin()
//    {
//        $token=request()->request("token");//会话凭证
//        $uid=token_decode($token);
//        $order_id=request()->request("order_id");//订单唯一id
//        $u_p_id=request()->request("u_p_id");//拼车表id
//        if(empty($token)){
//         $msg['state']=0;
//         $msg['msg']="用户会话出错";
//        }else{
//            //查询订单表中count和拼车表中的count
//            $pin_count=Db::table("user_pin")->where(['id'=>$u_p_id])->value("count");
//            $order=Db::table("order")->where(['order_id'=>$order_id])->find();
//            if(empty($pin_count)||empty($order['count'])){
//                $msg['state']=0;
//                $msg['data']=(object)[];
//                $msg['msg']="数值error";
//            }elseif($order['count']>$pin_count){
//                $msg['state']=0;
//                $msg['data']=(object)[];
//                $msg['msg']="data:error";
//            }else{
//                $msg['state']=1;
//                Db::table("order")->where(['order_id'=>$order_id,'uid'=>$uid])->update(['status'=>9,'price'=>'']);//更新拼车订单的信息
//                Db::table("user_pin")->where(['id'=>$u_p_id])->setDec("count",$order['count']);//更新拼车表中的count值
//                $msg['msg']="success";
//                $msg['data']=(object)[];
//            }
//        }
//       return json($msg);
//    }


    /**
     * * 用户切换状态列表
     **/
//    public function get_send_order_list()
//    {
//        $token = request()->request('token');
//        $uid = token_decode($token);
//        $status = request()->request('status');
//        $where['uid'] = $uid;//用户
//        if (!empty($status)) {//状态的更变
//            if ($status == 1) {
//                $where['status'] = ['in', '2,8'];//未进行或未支付
//            }elseif ($status == 2) {
//                $where['status'] = ['in', '3,4,5,6,7'];//进行中
//            }elseif ($status == 3) {
//                $where['status'] = ['in','9','10'];//已完成
//            }
//        }
//        $msg['state'] = 1;
//        $fields ='order_id,ident,cate_id,type,price,place_lng,place_lat,place_phone,place_name,place_truename,place_address,target_lng,target_lat,target_phone,target_name,target_truename,target_address,remark,image1,image2,image3,audio,issue_time,receive_time,complete_time,status,shop_charge,tip,express_charge,express_get_money,flag,discount,audio_length,require_time,express';
//        $page = request()->request('page') ? request()->request('page') : 1;
//        $pagesize = request()->request('pagesize') ? request()->request('pagesize') : 10;
//        $data = Db::table('order')->field($fields)->where($where)->page($page, $pagesize)->order('id desc')->select();
//        foreach($data as $k => $v){
//         if(!empty($v['express'])){
//                $express = Db::table('user')->where('id', $v['express'])->find();
//                $data[$k]['express_name'] = $express['true_name'];
//                $data[$k]['express_phone'] = $express['phone'];
//           }else{
//                $data[$k]['express_name'] = '';//抢单司机
//                $data[$k]['express_phone'] = '';
//            }
//        }
//        $msg['data'] = $data;
//        $msg['msg'] = '获取成功';
//        return json($msg);
//    }
    

    //获取接单司机的位置
    public function get_express_address()
    {
        $token = request()->request('token');
        $uid = token_decode($token);
        $order_id = request()->request('order_id');
        $msg['state'] = 0;
        $msg['data'] = json('');
        if (empty($order_id)) {
            $msg['msg'] = '参数错误';
        } else {
            $order = Db::table('order')->where(['uid' => $uid, 'order_id' => $order_id])->find();
            if (count($order) == 0){//与uid order_id 相关联的
                $msg['msg'] = '由于某种原因，您暂时不能查看配送员位置';
            } else {
                $msg['state'] = 1;
                $msg['data'] = Db::table('user')->field('lng,lat')->where('id', $order['express'])->find();
                $msg['msg'] = '获取成功';
            }
        }
        return json($msg);
    }
    
//    /**
//     ** 取消订单(用户)需要改东西
//     **/
//    public function cancel_order()
//    {
//        $token = request()->request('token');
//        $uid = token_decode($token);
//        $order_id = request()->request('order_id');
//        $msg['state'] = 0;
//        $msg['data'] = '';
//        if (empty($order_id)) {
//            $msg['msg'] = '参数错误';
//         }else{
//             $order = Db::table('order')->where(['order_id' => $order_id, 'uid' => $uid])->find();
//             if($order['status'] == 1){//司机尚未接单
//                $msg['state'] = 1;
//                Db::table('user_discounts')->where(['uid' => $uid, 'id' => $order['discount_id']])->update(['flag' => 0]);
//                Db::table('order')->where(['order_id' => $order_id, 'uid' => $uid])->update(['status' =>2]);
//                $msg['msg'] = '取消成功';
//              }elseif ($order['status'] >= 3 && $order['status'] <=9){
//                  if($order["type"]=="user_pin_car"){
//                   Db::table("user_pin")->where(["uid"=>$order["express"],'id'=>$order['u_p_id']])->setDec("count",$order['count']);                      
//                  }elseif(!empty($order['express'])){
//                         $msg['state']=0;
//                         $msg['msg'] = '您的订单已被司机接单，请联系司机取消订单后，再进行取消操作';
//                         $msg['data']="";
//                 }else{
//                      $pay_bool = false;
//                      if($order['payment'] == 'wxpay'){  
//                        //微信
//                        vendor('wxpayv_app.WxPay#Api');
//                        $input = new \WxPayRefund();
//                        $mchid = \WxPayConfig::$mchid;
//                        $input->SetOut_trade_no($order['order_id']);         //自己的订单号
//                        $input->SetTransaction_id(null);     //微信官方生成的订单流水号，在支付成功中有返回
//                        $input->SetOut_refund_no($order['order_id'] . '_exit');         //退款单号
//                        $input->SetTotal_fee($order['price'] * 100);         //订单标价金额，单位为分
//                        $input->SetRefund_fee($order['price'] * 100);            //退款总金额，订单总金额，单位为分，只能为整数
//                        $input->SetOp_user_id($mchid);
//                        $info = \WxPayApi::refund($input);
//                        if ($info['return_code'] == 'SUCCESS') {
//                            //退款申请成功
//                            $pay_bool = true;
//                            $msg['state'] = 1;
//                            $msg['msg'] = '操作成功';
//                        } else {
//                            //失败
//                            $msg['msg'] = '系统繁忙';
//                        }
//                    }else{
//                        //支付宝
//                        $this->alipay_config = Db::table("payment")->find();
//                        vendor('alipay.AopSdk');
//                        $aop = new \AopClient ();
//                        $aop->gatewayUrl = 'https://openapi.alipay.com/gateway.do';
//                        $aop->appId = $this->alipay_config['app_id'];
//                        $aop->rsaPrivateKey = $this->alipay_config['privatekey'];
//                        $aop->alipayrsaPublicKey = 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDDI6d306Q8fIfCOaTXyiUeJHkrIvYISRcc73s3vF1ZT7XN8RNPwJxo8pWaJMmvyTn9N4HQ632qJBVHf8sxHi/fEsraprwCtzvzQETrNRwVxLO5jVmRGi60j8Ue1efIlzPXV9je9mkjzOmdssymZkh2QhUrCmZYI/FCEa3/cNMW0QIDAQAB';
//                        $aop->apiVersion = '1.0';
//                        $aop->signType = 'RSA';
//                        $aop->postCharset = 'utf-8';
//                        $aop->format = 'json';
//                        vendor('alipay.aop.request.AlipayTradeRefundRequest');
//                        $request = new \AlipayTradeRefundRequest();
//                        $request->setBizContent("{" .
//                            "    \"out_trade_no\":\"" . $order_id . "\"," .
//                            "    \"trade_no\":\"\"," .
//                            "    \"refund_amount\":\"" . $order['price'] . "\"," .
//                            "    \"refund_reason\":\"跑帮郎退款\"," .
//                            "    \"out_request_no\":\"" . $order_id . "\"," .
//                            "    \"operator_id\":\"\"," .
//                            "    \"store_id\":\"\"," .
//                            "    \"terminal_id\":\"\"" .
//                            "}");
//                        $result = $aop->execute($request);
//                        $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
//                        $resultCode = $result->$responseNode->code;
//                        if(!empty($resultCode) && $resultCode == 10000){
//                            if ($result->$responseNode->msg == "Success" && $result->$responseNode->refund_fee == (string)$order['price']) {
//                                //退款申请成功
//                                $pay_bool = true;
//                                $msg['state'] = 1;
//                                $msg['msg'] = '操作成功';
//                            }
//                        }else{
//                            $msg['msg'] = '系统繁忙';
//                       }
//                    }
//                    //退款成功操作
//                    if($pay_bool){
//                        Db::table('order')->where(['order_id' => $order_id, 'uid' => $uid])->update(['status' =>2, 'system_money' =>0]);
//                        Db::table("user")->where("id",$order['express'])->setDec("money",$order['express_get_money']);
//                        Db::table("abandon_record")->insert(['uid' => $uid, 'order_id' => $order_id,'type'=>$order['type'], 'date' => $date]);
//                        Db::table('user_discounts')->where(['uid' => $uid, 'id' => $order['discount_id']])->update(['flag' => 0,'status'=>1]);
//                        push(md5($uid), json_encode(['type' => 1, 'message' => '退款成功，请注意查收', 'parameters' => $order_id, 'status' =>3]));
//                        insert_message($uid, '退款处理', '退款成功,请注意查收', '3', $order_id);
//                      }else{
//                        $msg['state']=0;
//                        $msg['msg']="操作失败";
//                    }
//                 }
//              }else{
//                $msg['msg'] = '非法操作';
//            }
//        }
//        return json($msg);
//    }
     //取消订单
    public function cancel_the_order()
    {      
        $token=request()->request("token");//会话凭证
        $uid= token_decode($token);//用户uid
        $order_id = request()->request('order_id');
        $msg['state']=0;
        $msg['data']="";
        $date = date("Y-m-d");
        $order=Db::table("order")->where("order_id",$order_id)->find();
        if($order['uid']!==$uid){
           $msg['msg']="非法操作";
         }else{
           //次数
           $check = Db::table("abandon_record")->where(['uid' => $uid,'type'=>$order['type'],'date' => $date])->count();
           if($check>=2){
               $msg['msg']="已取消两次,不能再取消";
                }else{
                    if($order['status']>=1 && $order["status"]<=5 && $order['type']=="run_for_you"||$order["type"]=="call_the_car"){
                     $msg['state'] = 1;
                     Db::table('order')->where(['order_id' => $order_id, 'uid' => $uid])->update(['status' =>2]);//取消
                     $msg['msg'] = '取消成功';
                    }elseif($order['status']>=6 && $order["status"]<=7&& $order['type']=="run_for_you"||$order["type"]=="call_the_car"){
                       $msg['state'] = 1;
                       Db::table("abandon_record")->insert(['uid' => $uid, 'order_id' => $order_id,'type'=>$order['type'], 'date' => $date]);   
                       $msg['msg'] = '联系司机取消后再取消';
                    }elseif($order['status']==1 && $order['type']=="book_a_room" ||$order['status']==3 && $order["type"]=="user_pin_car"){
                      //退款操作
                       $pay_bool=false;
                       if($order['payment']=="wxpay"){
                        //微信
                        vendor('wxpayv_app.WxPay#Api');
                        $input = new \WxPayRefund();
                        $mchid = \WxPayConfig::$mchid;
                        $input->SetOut_trade_no($order['order_id']);  //自己的订单号
                        $input->SetTransaction_id(null);     //微信官方生成的订单流水号，在支付成功中有返回
                        $input->SetOut_refund_no($order['order_id'] . '_exit');         //退款单号
                        $input->SetTotal_fee($order['price'] * 100);         //订单标价金额，单位为分
                        $input->SetRefund_fee($order['price'] * 100);            //退款总金额，订单总金额，单位为分，只能为整数
                        $input->SetOp_user_id($mchid);
                        $info = \WxPayApi::refund($input);
                        
                        if ($info['return_code'] == 'SUCCESS'){
                            //退款申请成功
                            $pay_bool = true;
                            $msg['state'] = 1;
                            $msg['msg'] = '操作成功';
                        } else {
                            $msg['msg'] = '系统繁忙';
                        }
                      }else{
                       //支付宝退款   
                        $this->alipay_config = Db::table("payment")->find();//读取退款操作
                        vendor('alipay.AopSdk');
                        $aop = new \AopClient ();
                        $aop->gatewayUrl = 'https://openapi.alipay.com/gateway.do';
                        $aop->appId = $this->alipay_config['app_id'];
                        $aop->rsaPrivateKey = $this->alipay_config['privatekey'];
                        $aop->alipayrsaPublicKey = 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDDI6d306Q8fIfCOaTXyiUeJHkrIvYISRcc73s3vF1ZT7XN8RNPwJxo8pWaJMmvyTn9N4HQ632qJBVHf8sxHi/fEsraprwCtzvzQETrNRwVxLO5jVmRGi60j8Ue1efIlzPXV9je9mkjzOmdssymZkh2QhUrCmZYI/FCEa3/cNMW0QIDAQAB';
                        $aop->apiVersion = '1.0';
                        $aop->signType = 'RSA';
                        $aop->postCharset = 'utf-8';
                        $aop->format = 'json';
                        vendor('alipay.aop.request.AlipayTradeRefundRequest');
                        $request = new \AlipayTradeRefundRequest();
                        $request->setBizContent("{" .
                            "    \"out_trade_no\":\"" . $order_id . "\"," .
                            "    \"trade_no\":\"\"," .
                            "    \"refund_amount\":\"" . $order['price'] . "\"," .
                            "    \"refund_reason\":\"咱县退款\"," .
                            "    \"out_request_no\":\"" . $order_id . "\"," .
                            "    \"operator_id\":\"\"," .
                            "    \"store_id\":\"\"," .
                            "    \"terminal_id\":\"\"" .
                            "}");
                        $result = $aop->execute($request);
                        $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
                        $resultCode = $result->$responseNode->code;
                        if(!empty($resultCode) && $resultCode == 10000){
                            if ($result->$responseNode->msg == "Success" && $result->$responseNode->refund_fee == (string)$order['price']){
                                //退款申请成功
                                $pay_bool = true;
                                $msg['state'] = 1;
                                $msg['msg'] = '操作成功';
                             }
                         }else{
                            $msg['msg'] = '系统繁忙';
                        }    
                     }
                    // var_dump($pay_bool);exit;
                     //退款成功后
                    if($pay_bool){
                         Db::table('order')->where(['order_id' =>$order_id, 'uid' => $uid])->update(['status' =>13, 'system_money' =>0]);
                        // Db::table("user")->where("id",$order['express'])->setDec("money",$order['express_get_money']);
                         Db::table("abandon_record")->insert(['uid' => $uid, 'order_id' => $order_id,'type'=>$order['type'], 'date' => $date]);
                         
                       if($order["discount_id"]){
                          Db::table('user_discounts')->where(['uid' => $uid, 'id' => $order['discount_id']])->update(['flag' => 0,'status'=>1]);
                        }
                        //如果是拼车类型，则需要在取消订单的时候,自动减少拼车人数
                       if($order["type"]=="user_pin_car"){
                            Db::table("user_pin")->where(["uid"=>$order["express"],'id'=>$order['u_p_id']])->setDec("count",$order['count']);
                            
                            
                        }
                        push(md5($uid), json_encode(['type' =>1, 'message' => '退款成功，请注意查收', 'parameters' => $order_id, 'status' =>3]));
                        insert_message($uid, '退款处理', '退款成功,请注意查收', '3', $order_id);
                       }else{
                         $msg['state']=0;
                         $msg['msg']="取消失败";
                       }
                    }elseif($order['status']==8 && $order["type"]=="user_pin_car"||$order['type']=="book_a_room"){       
                        $msg['state'] = 1;
//                        if($order['type']=="user_pin_car"){
//                         Db::table("user_pin")->where(["uid"=>$order["express"],'id'=>$order['u_p_id']])->setDec("count",$order['count']);
//                         
//                         
//                        }
                         Db::table('order')->where(['order_id' => $order_id, 'uid' => $uid])->update(['status' =>2]);//取消
                         $msg['msg'] = '取消成功';
                     }elseif($order['status']==3 && $order['type']=="book_a_room"){
                       $msg['state'] = 1;
                       $msg['msg'] = '联系司机取消后再取消';
                   }else{
                 $msg['msg']="非法操作";
                 }  
           }
        }
      return  json($msg);
   }

 
   
    /**
     * * 获取我的地址列表
     **/
     public function get_my_address_list()
    {
        $token = request()->request('token');
        $uid = token_decode($token);
        $msg['state'] = 1;
        $fields = 'id as address_id,address,name,phone,lng,lat,def';
        $page = request()->request('page') ? request()->request('page') : 1;
        $pagesize = request()->request('pagesize') ? request()->request('pagesize') : 10;
        $data = Db::table('address')->field($fields)->where('uid', $uid)->page($page, $pagesize)->order('def desc,id')->select();
        $msg['data'] = $data;
        $msg['msg'] = '获取成功';
        return json($msg);
    }

    /**
     * * 设置默认地址
     **/
    public function set_default_address()
    {
        $token = request()->request('token');
        $uid = token_decode($token);
        $id = request()->request('id');
        $msg['state'] = 0;
        $msg['data'] = '';
        if (empty($uid)) {
            $msg['msg'] = '参数错误';
        } else {
            $msg['msg'] = '操作成功';
            $msg['state'] = 1;
            Db::table('address')->where('uid', $uid)->update(['default' => 0]);
            Db::table('address')->where(['uid' => $uid, 'id' => $id])->update(['default' => 1]);
        }
        return json($msg);
    }

    /**
     * * 编辑地址
     **/
    public function edit_address()
    {
        $token = request()->request('token');
        $uid = token_decode($token);
        $address_id = request()->request('address_id');
        $msg['state'] = 0;
        $msg['data'] = '';
        $data = [];
        if (empty($uid)){
            $msg['msg'] = '参数错误';
        } else{
            $data['uid'] = $uid;
            $data['name'] = request()->request('name');
            $data['phone'] = request()->request('phone');
            $data['address'] = request()->request('address');
            $data['lng'] = request()->request('lng');
            $data['lat'] = request()->request('lat');
            if($address_id == ''){
                $count = Db::table('address')->where('uid', $uid)->count();
                if ($count == 0) {
                    $data['def'] = 1;
                }
                Db::table('address')->insert($data);
            }else{
               foreach ($data as $k => $v){
                    if ($v == '') {
                        unset($data[$k]);
                    }
                }
                Db::table('address')->where(['uid' => $uid, 'id' => $address_id])->update($data);
            }
            $msg['state'] = 1;
            $msg['msg'] = '添加成功';
        }
        return json($msg);
    }

    /**
     * * 删除地址
     **/
    public function del_address()
    {
        $token = request()->request('token');
        $uid = token_decode($token);
        $address_id = request()->request('address_id');
        $msg['state'] = 0;
        $msg['data'] = '';
        if(empty($uid) || empty($address_id)){
            $msg['msg'] = '参数错误';
        } else{
            $msg['state'] = 1;
            $check = Db::table('address')->where(['uid' => $uid, 'id' => $address_id])->find();
            if ($check['default'] == 1) {
                $new = Db::table('address')->where(['uid' => $uid])->where('id!=' . $check['id'])->find();
                Db::table('address')->where(['uid' => $uid, 'id' => $new['id']])->update(['default' => 1]);
            }
            Db::table('address')->where(['uid' => $uid, 'id' => $address_id])->delete();
            $msg['msg'] = '操作成功';
        }
        return json($msg);
    }

    //获取支付数据:与支付相关的先不碰
    public function order_pay()
    {
        $token = request()->request('token');
        $uid = token_decode($token);
        $order_id = request()->request('order_id');//商户id
        $msg['state'] = 1;
        $msg['data'] = '';
        $type = request()->request('type');//支付类型:微信/支付宝
        if (empty($uid) || empty($order_id) || ($type != 'wxpay' && $type != 'alipay')){
            $msg['msg'] = '参数错误';
        }else{
           $order = Db::table('order')->field('order_id,price,status')->where('order_id', $order_id)->find();
           if($order['status'] == 1){ 
                $IDENT = substr($order['order_id'], 0, 2);
                $new_id = $IDENT . date('ymdhis') . rand(1111, 9999);
                Db::table('order')->where('order_id', $order_id)->update(['order_id' => $new_id]);
                $order['order_id'] = $new_id;
                $data = $this->$type($order);
                $data['order_id'] = $order['order_id'];
                $msg['data'] = $data;
            }else{
                $msg['msg'] = '非法操作';
            }
        }
        return json($msg);
    }
    //获取订单应付金额
    public function order_discounts_price(){
     $token=request()->request("token");
     $uid = token_decode($token);//用户id
     $order_id = request()->request('order_id');  
     $discount_id=request()->request("discount_id");  
     $type=request()->request("type");//加上
     $msg['state']=0;
     $msg['data']=(object)[];
     $msg['msg']="数据过期";
     if(empty($uid)||empty($order_id)){
         $msg['state']=0;
         $msg['data']="";
         $msg['msg']="error:数据获取失败";
     }else{
         if($type=="wxpay"){
             $order=Db::table("order")->field("order_id,price,status")->where("order_id",$order_id)->find();
             if(empty($discount_id)){
                $msg['state']=1;
                if($order['status']==8){
                $IDENT = substr($order['order_id'], 0, 3);
                $new_id = $IDENT . date('ymdhis') . rand(1111, 9999);
                Db::table('order')->where('order_id', $order_id)->update(['order_id' => $new_id]);
                $order['order_id'] = $new_id;
                $data=$this->wxpay($order);
                $data['order_id']=$order["order_id"];
                $data['price']=$order["price"];
                $msg['data']=$data;
                $msg['msg']="success";
               }  
              }elseif($discount_id){
                $discount_money=Db::table("user_discounts")->where(['uid'=>$uid,'id'=>$discount_id,'status'=>1])->value('minus');
                $price=$order["price"]-$discount_money;
                if($order['status']==8){
                $msg['state']=1;
                $IDENT = substr($order['order_id'], 0, 3);
                $new_id = $IDENT . date('ymdhis') . rand(1111, 9999);
                Db::table('order')->where('order_id',$order_id)->update(['order_id' => $new_id,"discount_id"=>$discount_id]);
                $order['order_id']=$new_id;
                $order['price']=$price;
                $data=$this->wxpay($order);
                $data['order_id']=$order['order_id'];
                $data['price']=$price;
                $msg['data']=$data;
                $msg['msg']="success";
                }  
               }
              }elseif($type=="alipay"){
              $order=Db::table("order")->field("order_id,price,status")->where("order_id",$order_id)->find();
              if(empty($discount_id)){
               $msg['state']=1;
               $msg['data']=$order['price'];
               $msg['msg']="success:不使用优惠券"; 
              }elseif($discount_id){
              $msg['state']=1;
              $discount_money=Db::table("user_discounts")->where(['uid'=>$uid,'id'=>$discount_id,'status'=>1])->value('minus');
              $msg['data']=$order['price']-$discount_money;
              Db::table("order")->where(['uid'=>$uid,'order_id'=>$order['order_id']])->update(['discount_id'=>$discount_id]);
              $msg['msg']="success";
            }
          }
     }
     return json($msg);  
   }
    //回调
    public function pay_next()
    {
        $token = request()->request('token');
        $uid = token_decode($token);//用户id
        $order_id=request()->request('order_id');
        $type=request()->request('type');//支付宝或者微信
        $order =Db::table('order')->where(['uid'=>$uid,'order_id'=>$order_id])->find();
        $order_pay="";
        if($order['type']=="user_pin_car"||$order['type']=="book_a_room"){
           $order_pay=$order['price'];//
        }elseif($order['type']=="call_the_car"||$order['type']=="run_for_you"){
           if(empty($order['discount_id'])){
              $order_pay=$order['price'];
             }elseif($order['discount_id']){
             $discount_money=Db::table('user_discounts')->where(['id'=>$order['discount_id']])->value("minus"); 
             $order_pay=$order['price']-$discount_money;  
            }
        }
       // var_dump($order);exit;
        if(empty($uid)|| empty($order_id)){
              $msg['msg'] = '参数错误';
          }else{
             $pay_status = false;
            if($type == 'alipay'){
                $this->alipay_config = Db::table("payment")->find();//遍历数据库
                vendor('alipay.AopSdk');//网关
                $aop = new \AopClient ();
                $aop->gatewayUrl = 'https://openapi.alipay.com/gateway.do';
                $aop->appId = $this->alipay_config['app_id'];
                $aop->rsaPrivateKey = $this->alipay_config['privatekey'];
                $aop->alipayrsaPublicKey= 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDDI6d306Q8fIfCOaTXyiUeJHkrIvYISRcc73s3vF1ZT7XN8RNPwJxo8pWaJMmvyTn9N4HQ632qJBVHf8sxHi/fEsraprwCtzvzQETrNRwVxLO5jVmRGi60j8Ue1efIlzPXV9je9mkjzOmdssymZkh2QhUrCmZYI/FCEa3/cNMW0QIDAQAB';
                $aop->apiVersion = '1.0';
                $aop->signType = 'RSA';//加密方法
                $aop->postCharset = 'utf-8';
                $aop->format = 'json';
                vendor('alipay.aop.request.AlipayTradeQueryRequest');//引入网关文件
                $request = new \AlipayTradeQueryRequest ();
                $request->setBizContent("{" .
                    "    \"out_trade_no\":\"" . $order_id . "\"," .
                    "    \"trade_no\":\"\"" .
                    "  }");
                //设置订单号 out_trade_no 商户订单
                $result = $aop->execute($request);
                $responseNode = str_replace(".", "_", $request->getApiMethodName())."_response";
                $resultCode = $result->$responseNode->code;
                if(!empty($resultCode) && $resultCode =='10000'){
                   if($result->$responseNode->trade_status == "TRADE_SUCCESS" && $result->$responseNode->total_amount==(string)$order_pay){
                      $pay_status = true;                                                               //订单中的价格[计算后的]
                        $msg['state'] = 1;
                        $msg['msg'] = '支付成功';
                    }else{
                        $pay_status = false;
                        $msg['state']=0;
                        $msg['msg'] = '支付失败';
                    }
                 }else{
                    $msg['state']=0;
                    $msg['data']='';
                    $msg['msg'] = '支付失败';
                 }
                }elseif($type == 'wxpay'){
                 vendor('wxpayv_app.WxPay#Api');
                 $input = new \WxPayOrderQuery();
                 $input->SetOut_trade_no($order_id);
                 $result = \WxPayApi::orderQuery($input);
                 //var_dump($result);exit;
               if($result['result_code'] == "SUCCESS"){
                    if($result['trade_state'] == "SUCCESS" && $result['total_fee']==(string)$order_pay* 100){
                        
                        $pay_status = true;                                                
                        $msg['state'] = 1;
                        $msg['msg'] = '支付成功';
                    }else{
                        $msg['msg'] = '支付失败';
                        $pay_status = false;
                    }
                }
            }
            //支付成功
           if($pay_status){
                         $order=Db::table("order")->where(["order_id"=>$order_id])->find();  
                         $express_id=$order['express'];
                         $discount_id=$order['discount_id'];
                         Db::table('order')->where('order_id',$order_id)->update(['payment' =>$type]);
                         if($order['type']=="user_pin_car"&& $order['status']==8){
                           if(empty($discount_id)){
                             Db::table("order")->where(['order_id'=>$order_id])->update(['status'=>3]);
                             Db::table("user_pin")->where(['uid'=>$express_id,'id'=>$order['u_p_id']])->setInc('count',$order['count']); 
                             push(md5($express_id),json_encode(['type'=>2,'message'=>'用户已支付','parameters'=>$order_id,'status'=>13]));
                             insert_message($express_id,'订单提醒','用户已支付',13,$order_id);
                            }else{
                             Db::table("order")->where(['order_id'=>$order_id])->update(['status'=>3]);
                             Db::table("user_pin")->where(['uid'=>$express_id,'id'=>$order['u_p_id']])->setInc('count',$order['count']);
                             Db::table("user_discounts")->where(['id'=>$discount_id,'uid'=>$uid])->update(['status'=>2]);
                             push(md5($express_id),json_encode(['type'=>2,'message'=>'用户已支付','parameters'=>$order_id,'status'=>13]));
                             insert_message($express_id,'订单提醒','用户已支付',13,$order_id);
                            }
                         }elseif($order['type']=="call_the_car"||$order['type']=="run_for_you"&&$order['status']==8){
                           if(count($order)>0){
                            $msg['state']=1;
                          if(empty($discount_id)){
                             Db::table("order")->where(["express"=>$express_id,"order_id"=>$order_id])->update(["ident"=>"2",'status'=>9,'complete_time'=>time()]);
                            }else{
                             $discount_money=Db::table("user_discounts")->where('id',$discount_id)->value("minus");
                             $price=$order['price']-$discount_money;
                             Db::table("order")->where(["express"=>$express_id,"order_id"=>$order_id])->update(["ident"=>"1",'status'=>9,'price'=>$price,'discount_money'=>$discount_money,'complete_time'=>time()]); 
                             Db::table("user_discounts")->where(['id'=>$discount_id,'uid'=>$uid])->update(['status'=>2]);//
                           }
                           Db::table("earning")->insert(["order_id"=>$order_id,'money'=>$order['express_get_money'],'time'=>time(),"uid"=>$express_id,"type"=>"express"]);  //插入表中字段
                           $express_get_money=$order['express_get_money'];
                           Db::table("user")->where("id",$express_id)->setInc("money",$express_get_money);//步长自增长
                          //推送服务
                          push(md5($express_id),json_encode(['type'=>2,'message'=>'订单完成','parameters'=>$order_id,'status'=>13]));
                          insert_message($express_id,'订单提醒','订单完成',13,$order_id);
                          $msg['msg']="success:data";
                         }else{  
                          //
                          $msg['msg']='非法操作';
                        }
                       }elseif($order['type']=="book_a_room" && $order['status']==8){
                         $lng = $order['place_lng'];
                         $lat = $order['place_lat'];
                         $aid=Db::table("user")->where('id',$uid)->value("aid");
                         if(empty($discount_id)){
                             Db::table("order")->where(['order_id'=>$order_id])->update(['status'=>1]);
                             $min_size = 0;
                             $express_config = Db::table('express_config')->where('aid',$aid)->find();
                             $scope = $express_config['scope'];
                             $big_scope = $scope * 2;
                             $result_scope = $min_size;
                             while($scope <= $big_scope && $result_scope == $min_size) {
                             $result_scope = $this->big($lng, $lat, $scope,"book_a_room");
                               $scope++;
                             }
                            if($result_scope <= $min_size) {
                                  $msg['msg'] = '附近暂无酒店';
                                }elseif($result_scope > $min_size){
                                  $pi = $this->get_lat_lng($scope);
                                  $msg['state'] = 1;
                                  $this_time = time();
                                  $data['type']="book_a_room";
                                  $type_sql = 'select express_type from express_type_order where order_type like \'%' . $data['type'] . '%\'';
                                   $express_sql = 'select id from user where status=1 and business=1 and active_time>' . ($this_time - 300) . ' and isExpress=1 and express_type in(' . $type_sql . ') and lat > ' . $lat . '-' . $pi . ' and lat < ' . $lat . '+' . $pi . ' and lng > ' . $lng . '-' . $pi . ' and lng < ' . $lng . '+' . $pi . ' order by ACOS(SIN((' . $lat . ' * 3.1415) / 180 ) *SIN((lat * 3.1415) / 180 ) +COS((' . $lat . ' * 3.1415) / 180 ) * COS((lat * 3.1415) / 180 ) *COS((' . $lng . '* 3.1415) / 180 - (lng * 3.1415) / 180 ) ) * 6380 asc';
                                   $express = Db::table('user')->query($express_sql);
                                   $express_array = [];
                                   foreach ($express as $v) {
                                    $express_array[] = md5($v['id']);
                                    }
                                  push($express_array, json_encode(['type' => 2, 'message' => '附近有新订单啦~', 'parameters' => $data['order_id'], 'status' => 4]));
                                 // insert_message($express_array,'订单提醒','用户已支付',13,$order_id);
                                 }
                            }else{
                             Db::table("order")->where(['order_id'=>$order_id])->update(['status'=>1]);
                             Db::table("user_discounts")->where(['id'=>$discount_id,'uid'=>$uid])->update(['status'=>2]);
                             $min_size = 0;
                             $express_config = Db::table('express_config')->where('aid',$aid)->find();
                             $scope = $express_config['scope'];
                             $big_scope = $scope * 2;
                             $result_scope = $min_size;
                             while($scope <= $big_scope && $result_scope == $min_size) {
                             $result_scope = $this->big($lng, $lat, $scope,"book_a_room");
                               $scope++;
                               }
                             if($result_scope <= $min_size){
                                  $msg['msg'] = '附近暂无酒店';
                                }elseif($result_scope > $min_size){
                                  $pi = $this->get_lat_lng($scope);
                                  $msg['state'] = 1;
                                  $this_time = time();
                                  $data['type']="book_a_room";
                                  $type_sql = 'select express_type from express_type_order where order_type like \'%' . $data['type'] . '%\'';
                                   $express_sql = 'select id from user where status=1 and business=1 and active_time>' . ($this_time - 300) . ' and isExpress=1 and express_type in(' . $type_sql . ') and lat > ' . $lat . '-' . $pi . ' and lat < ' . $lat . '+' . $pi . ' and lng > ' . $lng . '-' . $pi . ' and lng < ' . $lng . '+' . $pi . ' order by ACOS(SIN((' . $lat . ' * 3.1415) / 180 ) *SIN((lat * 3.1415) / 180 ) +COS((' . $lat . ' * 3.1415) / 180 ) * COS((lat * 3.1415) / 180 ) *COS((' . $lng . '* 3.1415) / 180 - (lng * 3.1415) / 180 ) ) * 6380 asc';
                                   $express = Db::table('user')->query($express_sql);
                                   $express_array = [];
                                   foreach ($express as $v) {
                                    $express_array[] = md5($v['id']);
                                    }
                                  push($express_array, json_encode(['type' => 2, 'message' => '附近有新订单啦~', 'parameters' => $data['order_id'], 'status' => 4]));
                                  //insert_message($express_array,'订单提醒','用户已支付',13,$order_id);
                                 }
                               $msg['msg']="success:data";
                            }  
                   }
                  if(!empty($order['place_lat']) && !empty($order['place_lng'])) {
                     $lng = $order['place_lng'];
                     $lat = $order['place_lat'];
                  }else{
                     $lng = $order['target_lng'];
                     $lat = $order['target_lat'];
                  }
                  
                //推送附近司机
                $min_size = 0;
                $express_config = Db::table('express_config')->where('aid', $order['aid'])->find();
                $scope = $express_config['scope'];
                $big_scope = $scope * 2;
                $result_scope = $min_size;
                while ($scope <= $big_scope && $result_scope == $min_size){
                    $result_scope = $this->big($lng, $lat, $scope, $order['type']);
                    $scope++;
                }
               if($result_scope <= $min_size){
                    $msg['msg'] = '附近暂无司机';
               }elseif ($result_scope > $min_size){
                    $pi = $this->get_lat_lng($scope);
                    $msg['state'] = 1;
                    $this_time = time();
                    $type_sql = 'select express_type from express_type_order where order_type like \'%,' . $order['type'] . ',%\'';
                    $express_sql = 'select id from user where status=1 and id!=' . $uid . ' and business=1 and active_time>' . ($this_time - 300) . ' and isExpress=1 and express_type in(' . $type_sql . ') and lat > ' . $lat . '-' . $pi . ' and lat < ' . $lat . '+' . $pi . ' and lng > ' . $lng . '-' . $pi . ' and lng < ' . $lng . '+' . $pi . ' order by ACOS(SIN((' . $lat . ' * 3.1415) / 180 ) *SIN((lat * 3.1415) / 180 ) +COS((' . $lat . ' * 3.1415) / 180 ) * COS((lat * 3.1415) / 180 ) *COS((' . $lng . '* 3.1415) / 180 - (lng * 3.1415) / 180 ) ) * 6380 asc';
                    $express = Db::table('user')->query($express_sql);
                    $express_array = [];
                    foreach($express as $v){
                        $express_array[] = md5($v['id']);
                    }
                    push($express_array, json_encode(['type' => 2, 'message' => '附近有新订单啦~', 'parameters' => $order['order_id'], 'status' => 4]));
                    $msg['msg'] = '操作成功';
                }
            }
        }
        return json($msg);
    }

    // 对签名字符串转义
    private function createLinkstring($para)
    {
        $arg = '';
        while (list($key, $val) = each($para)) {
            $arg .= $key . '="' . $val . '"&';
        }
        //去掉最后一个&字符
        $arg = substr($arg, 0, count($arg) - 2);
        //如果存在转义字符，那么去掉转义
        if (get_magic_quotes_gpc()) {
            $arg = stripslashes($arg);
        }
        return $arg;
    }
    
    // 签名生成订单信息
    private function rsaSign($data)
    {
        $priKey = "-----BEGIN RSA PRIVATE KEY-----\n" .
            wordwrap($this->alipay_config['privatekey'], 64, "\n", true) .
            "\n-----END RSA PRIVATE KEY-----";
        $res = openssl_get_privatekey($priKey);
        openssl_sign($data, $sign, $res);
        openssl_free_key($res);
        $sign = base64_encode($sign);
        $sign = urlencode($sign);
        return $sign;
    }

    //alipay
    public function alipay($data)
    {
        //var_dump($data);
        $this->alipay_config =Db::table("payment")->find();
        // 支付宝合作者身份ID，以2088开头的16位纯数字
        $partner = $this->alipay_config['partner'];
        // 支付宝账号
        $seller_id = $this->alipay_config['seller_id'];
        $order= Db::table('order')->where(['status'=>8,'order_id'=>$data['order_id']])->find();
        if($order['type']=="user_pin_car"){
            $order_pay=$data['price'];
         }elseif($order['type']=="call_the_car"||$order['type']=="run_for_you"){
           if(empty($order['discount_id'])){
            $order_pay=$data['price'];
            }else{
            $discount_money=Db::table('user_discounts')->where(['id'=>$order['discount_id']])->value("minus"); 
            $order_pay=$order['price']-$discount_money; 
          }
        }
        // 订单详情
        $body = '咱县打车';
        $parameter = array(
            'service' => 'mobile.securitypay.pay',   // 必填，接口名称，固定值
            'partner' => $partner,                   // 必填，合作商户号
            '_input_charset' => 'UTF-8',                    // 必填，参数编码字符集
            'out_trade_no' => $data['order_id'],          // 必填，商户网站唯一订单号
            'subject' => "发布订单：" .$body,           // 必填，商品名称
            'payment_type' => '1',                        // 必填，支付类型
            //'trade_no'   => $data['orderid'],
            'seller_id' => $seller_id,                 // 必填，卖家支付宝账号
            'total_fee' =>$order_pay,             // 必填，总金额，取值范围为[0.01,100000000.00]
            'body' => $body,                      // 必填，商品详情
        );

        //生成需要签名的订单
        $orderInfo = $this->createLinkstring($parameter);
        //签名
        $sign = $this->rsaSign($orderInfo);
        //生成订单
        $json = $orderInfo . '&sign="' . $sign . '"&sign_type="RSA"';
        return json($json);
    }
    //weixin
    public function wxpay($data)
    {
        vendor('wxpayv_app.WxPay#Api');
        //订单详情
        $body = '咱县打车';
        $url = \think\Url::build('wx_call_back', 'token=' . request()->request('token') . '&order_id=' . $data['order_id'], true, true);
        $unifiedOrder = new \WxPayUnifiedOrder();
        $unifiedOrder->SetBody($body);
        $unifiedOrder->SetOut_trade_no($data['order_id']);
        $unifiedOrder->SetTotal_fee($data['price'] * 100);
        $unifiedOrder->SetNotify_url($url);
        $unifiedOrder->SetTrade_type("APP");
        $result = \WxPayApi::unifiedOrder($unifiedOrder);
        return $result;
    }

    //微信回调
    public function wx_call_back()
    {

        $xml = file_get_contents('php://input');
        $xml_array = simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA);
        file_put_contents(APP_PATH . '/1.txt', print_r($xml_array, true));
        $transaction_id = $xml_array->transaction_id;
        $token = request()->request('token');
        $uid = token_decode($token);
        $order_id = request()->request('order_id');
        $order = Db::table('order')->where('order_id', $order_id)->find();
        /*if($result['trade_state'] == "SUCCESS" && $result['total_fee'] == $order['price']*100){

            Db::table('order')->where('order_id', $order_id)->update(['status' => 2, 'payment' => 'wxpay','transaction_id'=>$transaction_id]);

            if (!empty($order['place_lat']) && !empty($order['place_lng'])) {
                $lng = $order['place_lng'];
                $lat = $order['place_lat'];
            } else{
                $lng = $order['target_lng'];
                $lat = $order['target_lat'];
            }

            //推送附近配送员
            $min_size = 0;
            $express_config = Db::table('express_config')->where('aid', $order['aid'])->find();
            $scope = $express_config['scope'];
            $big_scope = $scope * 2;
            $result_scope = $min_size;
            while ($scope <= $big_scope && $result_scope == $min_size) {
                $result_scope = $this->big($lng, $lat, $scope, $order['type']);
                $scope++;
            }

            if ($result_scope <= $min_size) {
                $msg['msg'] = '附近暂无配送员';
            } elseif ($result_scope > $min_size) {
                $pi = $this->get_lat_lng($scope);
                $msg['state'] = 1;
                $this_time = time();
                $type_sql = 'select express_type from express_type_order where order_type like \'%,' . $order['type'] . ',%\'';
                $express_sql = 'select id from user where status=1 and id!='.$uid.' and business=1 and active_time>' . ($this_time - 300) . ' and isExpress=1 and express_type in(' . $type_sql . ') and lat > ' . $lat . '-' . $pi . ' and lat < ' . $lat . '+' . $pi . ' and lng > ' . $lng . '-' . $pi . ' and lng < ' . $lng . '+' . $pi . ' order by ACOS(SIN((' . $lat . ' * 3.1415) / 180 ) *SIN((lat * 3.1415) / 180 ) +COS((' . $lat . ' * 3.1415) / 180 ) * COS((lat * 3.1415) / 180 ) *COS((' . $lng . '* 3.1415) / 180 - (lng * 3.1415) / 180 ) ) * 6380 asc';
                $express = Db::table('user')->query($express_sql);
                $express_array = [];
                foreach ($express as $v) {
                    $express_array[] = md5($v['id']);
                }
                push($express_array, json_encode(['type' => 2, 'message' => '附近有新订单啦~', 'parameters' => $order['order_id'], 'status' => 4]));
            }

        }*/
    }
    
    //用户使用帮助
    public function get_use_help()
    {
        $content = '<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" /><title>使用帮助</title>';
        return $content .Db::table('notice')->where('title', '用户使用帮助')->value('content');
    }

//    //本地信息列表
//    public function get_bulletin_list()
//    {
//        $lng = request()->request('lng');
//        $lat = request()->request('lat');
//        $area = request()->request('area') ? request()->request('area') : '郓城县';
//        $msg['state'] = 0;
//        $msg['data'] = [];
//        if (empty($lng) || empty($lat) || empty($area)) {
//            $msg['msg'] = '参数错误';
//        } else {
//            $msg['state'] = 1;
//            $aid = Db::table('area')->where('name', 'like', '%' . $area . '%')->value('id');
//            $fields = 'title,image,description,lng,lat,phone';
//            $page = request()->request('page') ? request()->request('page') : 1;
//            $pagesize = request()->request('pagesize') ? request()->request('pagesize') : 10;
//            $data = Db::table('bulletin')->field($fields)->where(['aid' => $aid, 'status' => 1])->page($page, $pagesize)->order('sort desc,ACOS(SIN((' . $lat . ' * 3.1415) / 180 ) *SIN((lat * 3.1415) / 180 ) +COS((' . $lat . ' * 3.1415) / 180 ) * COS((lat * 3.1415) / 180 ) *COS((' . $lng . '* 3.1415) / 180 - (lng * 3.1415) / 180 ) ) * 6380 asc')->select();
//            foreach ($data as $k => $v) {
//                $data[$k]['distance'] = strval(round($this->getDistance($lat, $lng, $v['lat'], $v['lng']) / 1000, 2));
//                unset($data[$k]['lng']);
//                unset($data[$k]['lat']);
//            }
//            $msg['data'] = $data;
//            $msg['msg'] = '获取成功';
//        }
//        return json($msg);
//    }

//咱县头条列表
   public function get_toptins_list(){
    $lng=request()->request("lng"); //经度
    $lat=request()->request("lat");//纬度
    $area=request()->request("area")?request()->request("area"):"郓城县";
    $msg['state']=0;
    $data=[];
    if(empty($lng)||empty($lat)||empty($area)){
       $msg['msg']="error:lng&lat&area";
    }else{
      $msg['state']=1;
      $aid=Db::table("area")->where('name','like','%'.$area .'%')->value("id");
      unset($area);
      $fields = 'id as topid,title,image,image1,image2,description,lng,lat';//内容:
      $page=request()->request("page")?request()->request("page"):1;
      $pagesize=request()->request("pagesize")?request()->request("pagesize"):10;
      $data=Db::table("bulletin")->field($fields)->where(['aid'=>$aid,'status'=>1,'type'=>1])->page($page,$pagesize)->select();
       foreach ($data as $k => $v) {
                $data[$k]['distance'] = strval(round($this->getDistance($lat, $lng, $v['lat'], $v['lng']) / 1000, 2));
                unset($data[$k]['lng']);
                unset($data[$k]['lat']);
            }
     $msg['data']=$data;
     $msg['msg']="success";
     }
    return json($msg);
   }
  

   //咱县书屋列表
   public function get_bookroom_list(){
     $lng=request()->request("lng");
     $lat=request()->request("lat");
     $area=request()->request("area")?request()->request("area"):"郓城";
     $msg['state']=0;
     $data=[];
     if(empty($lng)||empty($lat)||empty($area)){
         $msg['msg']="error:data";
     }else{
       $msg['state']=1;
       $aid=Db::table("area")->where("name","like",'%'.$area.'%')->value("id");
       unset($area);
       $fields="id as bookid,title,image,description,lng,lat";  //书屋内容
       $page=request()->request("page")?request()->request("page"):1;
       $pagesize=request()->request("pagesize")?request()->request("pagesize"):10;
       $data=Db::table("bulletin")->field($fields)->where(["aid"=>$aid,"status"=>1,"type"=>2])->page($page,$pagesize)->select();
       foreach($data as $k=>$v){
           $data[$k]['distance'] = strval(round($this->getDistance($lat, $lng, $v['lat'], $v['lng']) / 1000, 2));
               unset($data[$k]['lng']);
               unset($data[$k]['lat']);
       }
       $msg['data']=$data;
       $msg['msg']="success";
     }
     return json($msg);
   }
   

  //优惠券描述
    public function discounts_description()
    {
        $description = '';
        $data = Db::table('discounts')->group('type')->select();
        foreach ($data as $v) {
            $description .= $v['description'] . '<br>';
        }
        $content = '<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" /><title>优惠券使用帮助</title>';
        halt($content.$description);
        return $content . $description;
    }

    /****
     * 用户评论相关接口    user/user_to_star  token order_id star comments 
     * ***/
    public function user_to_star(){
       $token=request()->request("token");
       $data=[];
       if(empty($token)){
        $msg['state']=0;
        $msg['data']="";
        $msg['msg']="error:token";
       }else{
          $data['uid']= token_decode($token);
          $data['order_id']=request()->request("order_id");
          $data['star']=request()->request("star");
          $data['comments']=request()->request("comments");
          $data['status']=2;//已评论
          Db::table("user_comments")->insert($data);
          $msg['state']=1;
          $msg['data']="";
          $msg['msg']="success!";
       }
      return json($msg);
    }



    //小程序
    public function mini_call_back()
    {
        $xml = file_get_contents('php://input');
        libxml_disable_entity_loader(true);
        $array = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        file_put_contents(APP_PATH . '1.txt', print_r($array, true));
        $order_id = $array['out_trade_no'];
        $appid = $array['appid'];
        $mch_id = $array['mch_id'];
        $total_fee = $array['total_fee'];
        $order = Db::table('order')->where('order_id', $order_id)->find();
        if(count($order) > 0){
            $wxconfig = Db::table('wxpay')->where('type', 'mini')->find();
            if ($wxconfig['appid'] == $appid && $wxconfig['mchid'] == $mch_id) {
                Db::table('order')->where('order_id', $order_id)->update(['status' => 2, 'payment' => 'wxpay']);

                if (!empty($order['place_lat']) && !empty($order['place_lng'])) {
                    $lng = $order['place_lng'];
                    $lat = $order['place_lat'];
                } else {
                    $lng = $order['target_lng'];
                    $lat = $order['target_lat'];
                }

                //推送附近配送员
                $min_size = 0;
                $express_config = Db::table('express_config')->where('aid', $order['aid'])->find();
                $scope = $express_config['scope'];
                $big_scope = $scope * 2;
                $result_scope = $min_size;
                while($scope <= $big_scope && $result_scope == $min_size) {
                    $result_scope = $this->big($lng, $lat, $scope, $order['type']);
                    $scope++;
                }
                if ($result_scope <= $min_size) {
                    $msg['msg'] = '附近暂无配送员';
                }elseif ($result_scope > $min_size){
                    $pi = $this->get_lat_lng($scope);
                    $msg['state'] = 1;
                    $this_time = time();
                    $type_sql = 'select express_type from express_type_order where order_type like \'%,' . $order['type'] . ',%\'';
                    $express_sql = 'select id from user where status=1 and business=1 and active_time>' . ($this_time - 300) . ' and isExpress=1 and express_type in(' . $type_sql . ') and lat > ' . $lat . '-' . $pi . ' and lat < ' . $lat . '+' . $pi . ' and lng > ' . $lng . '-' . $pi . ' and lng < ' . $lng . '+' . $pi . ' order by ACOS(SIN((' . $lat . ' * 3.1415) / 180 ) *SIN((lat * 3.1415) / 180 ) +COS((' . $lat . ' * 3.1415) / 180 ) * COS((lat * 3.1415) / 180 ) *COS((' . $lng . '* 3.1415) / 180 - (lng * 3.1415) / 180 ) ) * 6380 asc';
                    $express = Db::table('user')->query($express_sql);
                    $express_array = [];
                    foreach ($express as $v) {
                        $express_array[] = md5($v['id']);
                    }
                    push($express_array, json_encode(['type' => 2, 'message' => '附近有新订单啦~', 'parameters' => $order['order_id'], 'status' => 4]));
                    $msg['msg'] = '操作成功';
                }

                return '<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>';
            } else {
                return '<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[ERROR]]></return_msg></xml>';
            }
        }
    }

    public function test()
    {
        /*
        $pcm = system(APP_PATH . 'silk_v3_decoder.exe ' . APP_PATH . 'cache/1.silk ' . APP_PATH . 'cache/1.pcm', $out1);
        $mp3 = system(APP_PATH . 'ffmpeg.exe -y -f s16le -ar 24000 -ac 1 -i ' . APP_PATH . 'cache/1.pcm ' . APP_PATH . 'cache/1.mp3', $out2);
        */
    }

    //小程序
    public function mini_pay()
    {
        /*vendor("wxpay.WxPayApi");
        $order_id = time() . rand(1111, 9999);
        $openid = 'o89Ig0b8sD1KCyaHBSYbtrSvII7A';
        $wxpay = new \WxPayApi();
        $back_url = 'http://niu.wm0530.com/nav/app/user/test';
        $config = Db::table('wxpay')->where('type', 'mini')->find();
        $result = $wxpay->config(['appid' => $config['appid'], 'mch_id' => $config['mchid'], 'key' => $config['key']], '跑帮郎付款', $back_url, $order_id, '1', 'JSAPI', '39.81.252.95', $openid);
        print_r($result);*/
        
        vendor("wxpay.WxPayApi");
        $order_id = request()->request('order_id');
        $order = Db::table('order')->where('order_id',$order_id)->find();
        $openid = request()->request('mini');
        $wxpay = new \WxPayApi();
        $back_url = \think\Url::build('mini_call_back', '', true, true);
        if (request()->request('wxd')) {
            $config = Db::table('wxpay')->where('type', 'wxd')->find();
        } else {
            $config = Db::table('wxpay')->where('type', 'mini')->find();
        }
        $result = $wxpay->config(['appid' => $config['appid'], 'mch_id' => $config['mchid'], 'key' => $config['key']], '跑帮郎付款', $back_url, $order_id, $order['price'] * 100, 'JSAPI', null, $openid);
        return json($result);
    }

    /*
     * 待支付列表 user/get_user_topay()
     * 跟用户相关的未支付的订单都算其中包括拼车订单
     */
    public function get_user_topay(){
      $token=request()->request("token");
      $uid=token_decode($token);
      $where['status']=['in','8'];//待支付状态 、status/uid
      $msg['state']=0;
      if(empty($token)){
          $msg['state']=0;
          $msg['msg']="error:token";
       }else{
        $msg['state']=1;
        $where['uid']=$uid;//和订单相关联的用户自己的id
       //类型
        $page = request()->request('page') ? request()->request('page') : 1;
        $pagesize = request()->request('pagesize') ? request()->request('pagesize') : 10;
        $fields="type,place_truename,place_phone,order_id,place_address,target_address,audio,audio_length,express,price,status,receive_time,place_name,target_name,issue_time";
        $data=Db::table("order")->field($fields)->where($where)->page($page,$pagesize)->select();
        foreach($data as $k=>$v){
        if(!empty($v['express'])){
               $user=Db::table("user")->where('id',$v['express'])->find();
               $star_status=Db::table("user_comments")->where(['uid'=>$uid,'order_id'=>$v['order_id']])->value("status");
               if(!$star_status){
                 $data[$k]['star_status']=1;
               }else{
                $data[$k]['star_status']=$star_status;     
               }
              $data[$k]['true_name']=$user['true_name']; //司机姓名
              $data[$k]['phone']=$user['phone'];//司机手机
             
            }else{
               $data[$k]['true_name']='';//姓名
               $data[$k]['phone']='';//手机号
           }
       
        }
        
        $msg['data']=$data;
        $msg['msg']="success!";
      }
     return json($msg);
    }
    /*user/get_order_list
     *进行中的订单列表[状态:3,4,5,6,7]
     */
    public function get_ordering_list(){
     $token=request()->request("token");
     $uid= token_decode($token);//uid
     $where['status']=['in','1,3,4,5,6,7'];//status
     $page = request()->request('page') ? request()->request('page') :1;
     $pagesize = request()->request('pagesize') ? request()->request('pagesize'):10;
     if(empty($token)){
        $msg['state']=0;
        $msg['msg']="error:token";
     }else{
       //有值的情形下
       $msg['state']=1;
       $where['uid']=$uid;
       $fields="type,place_truename,place_phone,order_id,place_address,target_address,audio,audio_length,express,status,receive_time,place_name,target_name,issue_time";
       $data=Db::table("order")->field($fields)->where($where)->page($page,$pagesize)->order("require_time desc")->select();
         foreach($data as $k=>$v){
          if(empty($v['target_address'])){
            $data[$k]['target_address']="";
          }  
          if(!empty($v['express'])){   
          $user=Db::table("user")->where('id',$v['express'])->find();
          $star_status=Db::table("user_comments")->where(['uid'=>$uid,'order_id'=>$v['order_id']])->value("status");
          if(!$star_status){
              $data[$k]['star_status']=1;
           }else{
            $data[$k]['star_status']=$star_status;
          }
           $data[$k]['true_name']=$user["true_name"]; //真实姓名
           $data[$k]['phone']=$user['phone'];//电话
          }else{
           $data[$k]['true_name']='';//
           $data[$k]['phone']="";
          }
        }
        $msg['data']=$data;
        $msg['msg']="success!";
     }
     return json($msg);
    }
    //
    public function get_car_status(){
     $token=request()->request("token");  
     $where['uid']= token_decode($token);//uid
     $where['status']=['in','1,3,4,5,6,7,8'];//status
     $where['type']="call_the_car"; 
     if(empty($token)){
       $msg['state']=0;
       $msg['data']=""; 
       $msg['msg']="订单没了";
     }else{
       $msg['state']=1;
       $fields="order_id,status,place_lng,place_lat,target_lng,target_lat,price,place_area,target_area";
       $order_data=Db::table("order")->field($fields)->where($where)->find();
       if($order_data){
          if($order_data['status'] != '8'){
            $order_data['price'] = '';
         }
         $msg['data']=$order_data;
        }else{
           $msg['data']=(object)[]; 
        }
        $msg['msg']="yes,success";  
      }
      return json($msg);   
   }
    
    /***
     * 完成订单列表 按时间排序倒序
     * ****/
    public function get_ordered_list(){
     $token=request()->request("token");
     $uid=token_decode($token); //uid
     $where['status']=['in',"2,9,13"]; //2,已取消,9,已支付，13,已退款
     $data=[];
     if(empty($token)){
        $msg['state']=0;
        $msg['msg']="error:token";
     }else{
       $msg['state']=1;
       $where['uid']=$uid;//用户uid
       $page = request()->request('page') ? request()->request('page') :1;
       $pagesize = request()->request('pagesize') ? request()->request('pagesize'):10;
       $fields="type,place_truename,place_phone,order_id,place_address,target_address,audio,audio_length,express,status,receive_time,place_name,target_name,issue_time";
       $data=Db::table("order")->field($fields)->where($where)->page($page,$pagesize)->order(['complete_time'=>'desc'])->select();
       foreach($data as $k=>$v){
         if(!empty($v['express'])){
           $user=Db::table("user")->where('id',$v['express'])->find();
           $star_status=Db::table("user_comments")->where(['uid'=>$uid,'order_id'=>$v['order_id']])->value("status");
           if(!$star_status){
             $data[$k]['star_status']=1;
            }else{
             $data[$k]['star_status']=$star_status; 
            }
           $data[$k]['true_name']=$user['true_name'];//司机名
           $data[$k]['phone']=$user["phone"];//司机联系方式
         }else{
           $data[$k]['true_name']="";
           $data[$k]['phone']="";
         }
       }
        $msg['data']=$data;
        $msg['msg']="success";
      }
     return json($msg);
    }
    
    

    /***
     * 分享优惠券
     *
     * ****/
    public function user_to_share(){
      $token=request()->request("token");
      $uid= token_decode($token);
      $aid=Db::table("user")->where('id',$uid)->value("aid");
      $msg['state']=1;
      $msg['data']=Db::table("discounts")->field("type,description")->where('aid',$aid)->find();
      $msg['data']['invitation']=$uid;
      $msg['msg']="success";
      return json($msg);
    }
    /***用户优惠券列表
     * 跟用户相关联的优惠券
     * uid user_discounts
     * *****/
    public function user_discounts_list(){
     $token=request()->request("token");
     $uid= token_decode($token);
     $data=[];
     if(empty($token)){
       $msg['state']=0;
       $msg['data']=(object)[];
       $msg['msg']="error";
     }else{
      $msg['state']=1;
      $phone=Db::table("user")->where('id',$uid)->value("phone");
      $this_time=time();
      $data=Db::table("user_discounts")->field("id as discount_id,aid,discription,due_date,minus")->where(['uid'=>$uid,'status'=>1])->where("due_date>=".$this_time)->select();
      foreach($data as $k=>$v){
          $aid=$v['aid'];
          $data[$k]['area']=Db::table('area')->where('id',$aid)->value('name');
          $data[$k]['phone']=$phone;
      }
      $msg['data']=$data;
      $msg['msg']="success";
     }
     return json($msg);
    }

   //用户端订单详情
    public function get_order_detail(){
     $token=request()->request("token");
     $uid= token_decode($token);
     $order_id=request()->request("order_id");
     if(empty($token)||empty($order_id)){
         $msg['state']=0;
         $msg['msg']="error:order_id||token";
     }else{
        $msg['state']=1;
        $fields="order_id,audio_length,place_area,target_area,audio,express,require_time,place_truename,place_phone,place_address,target_address,type,issue_time,express_charge,tip,price,image1,image2,image3,status,discount_money";
        $order_detail=Db::table("order")->field($fields)->where(['uid'=>$uid,'order_id'=>$order_id])->find();
        //司机的相关信息
        $express=Db::table("user")->field("phone,lng,lat,true_name")->where("id",$order_detail['express'])->find();
        //订单评价相关信息
        $user_comments=Db::table("user_comments")->field("star,comments,status")->where(['order_id'=>$order_id,'uid'=>$uid])->find();    
        if(!$user_comments){
            $user_comments['star'] ="";
            $user_comments['comments'] ="";
            $user_comments['status'] =1;
        }
        $order_detail['user_star']=$user_comments['star'];
        $order_detail['user_comments']=$user_comments['comments'];
        $order_detail['user_status']=$user_comments["status"];
        if(!$express){
           $express['phone']="";
           $express['true_name']="";
        }
        $order_detail['driver_phone']=$express['phone'];
        $order_detail['driver_name']=$express['true_name'];
        $msg['data']=$order_detail;
        $msg['msg']="success";
     }
     return json($msg);
   }
// get_pin_order_detail
    //拼车订单详情页
  public function get_pin_order_detail(){
      $token=request()->request("token"); 
      $uid= token_decode($token);
      $order_id=request()->request("order_id"); 
      if(empty($token)||empty($order_id)){
         $msg['state']=0;
         $msg['msg']="error:order_id||token";
       }else{
        $msg['state']=1;
        $fields="order_id,place_area,require_time,target_area,express,receive_time,place_lng,place_lat,place_truename,place_phone,place_address,type,issue_time,express_charge,price,status,discount_money,target_truename,target_name,place_name,count,target_phone,u_p_id";
        $order_detail=Db::table("order")->field($fields)->where(['uid'=>$uid,'order_id'=>$order_id])->find();
        //司机的相关信息
        $order_detail['leave_time']=$order_detail['issue_time'];//离开时间
        unset($order_detail['issue_time']);
        $order_detail['start_address']=$order_detail['place_name'];//拼车起始地点
        $order_detail['end_address']=$order_detail['target_name'];//拼车结束地点
        $order_detail['people_number']=$order_detail['count'];
        $order_detail['time_get_car']=$order_detail["require_time"];
        unset($order_detail["require_time"]);
        unset($order_detail['count']);
        unset($order_detail['place_name']);
        unset($order_detail['target_name']);
        //订单评价相关信息
        $car_number=Db::table("express_check")->where("uid",$order_detail['express'])->value("car_number");//车牌号
        $user_comments=Db::table("user_comments")->field("star,comments,status")->where(['order_id'=>$order_id,'uid'=>$uid])->find();    
        if(!$user_comments){
            $user_comments['star'] ="";
            $user_comments['comments'] ="";
            $user_comments['status'] =1;
        }
        $order_detail['user_star']=$user_comments['star'];//评星
        $order_detail['user_comments']=$user_comments['comments'];//评价内容
        $order_detail['user_status']=$user_comments["status"];//评价状态
        //拼车相关的信息
        $pin_data=Db::table("user_pin")->where(['id'=>$order_detail['u_p_id'],'uid'=>$order_detail['express']])->find();
        $order_detail['count']=$pin_data['count'];//当前拼车人数
        $order_detail['total_count']=$pin_data['total_count'];//拼车总人数
        $order_detail['car_number']=$car_number;
        $order_detail['pin_price']=$order_detail['express_charge'];
        unset($order_detail['express_charge']);
        $order_detail['discount_price']=$order_detail['discount_money'];
        unset($order_detail['discount_money']);
        $order_detail['driver_phone']=$order_detail['target_phone'];
        $order_detail['driver_name']=$order_detail['target_truename'];
        unset($order_detail['target_phone']);
        unset($order_detail['target_truename']);
        $msg['data']=$order_detail;
        $msg['msg']="success"; 
       }  
    return json($msg);    
  }
  
  //订个房订单详情
 public function get_book_order_detail()
{       
     $token=request()->request("token");
     $uid= token_decode($token);
     $order_id=request()->request("order_id");
     if(empty($token)||empty($order_id)){
         $msg['state']=0;
         $msg['msg']="error:order_id||token";
     }else{
        $msg['state']=1;
        $fields="order_id,audio_length,place_area,target_area,audio,express,require_time,place_truename,place_phone,place_address,target_address,type,issue_time,express_charge,price,image1,image2,image3,status,discount_money";
        $order_detail=Db::table("order")->field($fields)->where(['uid'=>$uid,'order_id'=>$order_id])->find();
        //司机的相关信息
        $express=Db::table("user")->field("phone,lng,lat,true_name")->where("id",$order_detail['express'])->find();
        //订单评价相关信息
        $user_comments=Db::table("user_comments")->field("star,comments,status")->where(['order_id'=>$order_id,'uid'=>$uid])->find();    
        if(!$user_comments){
            $user_comments['star'] ="";
            $user_comments['comments'] ="";
            $user_comments['status'] =1;
        }
        $order_detail['user_star']=$user_comments['star'];
        $order_detail['user_comments']=$user_comments['comments'];
        $order_detail['user_status']=$user_comments["status"];
        if(!$express){
           $express['phone']="";
           $express['true_name']="";
        }
        $order_detail['driver_phone']=$express['phone'];
        $order_detail['driver_name']=$express['true_name'];
        $msg['data']=$order_detail;
        $msg['msg']="success";
     }
     return json($msg);
     
 }
 
 //用户分享优惠券
  
  
  
  
  
 
}
